<?php

class FinanceAction extends CommonAction
{
    public function index()
	{
		$this->fiscalyp_list();
    }
	
	/* 货币 */
	
	public function currmas_list()
	{
		$datalist = M("Currmas")->where("status_flg in ('Y','N')") -> order("flag desc,status_flg asc,orderid asc")->select();
		$this->assign("datalist",$datalist);
		$this->display();
    }
	public function currmas_add()
	{		
		$orderid=M("Currmas")->getField("max(orderid)+1");
		$this->assign("orderid",$orderid==null?1:$orderid);
		$this->display();
    }
	public function currmas_add_save()
	{
		$model = D("Currmas");
		$this->assign("jumpUrl",U('Finance/currmas_list'));
		if ($model->create())
		{			
			$model->posttime=time();
			$model->diyinfo=serialize($_POST['diyinfo']);
			$classid=$model->add();
			if($_POST['flag']=='Y')
			{
				$data['flag']='N';
				$model->where('id not in ('.$classid.')')->save($data);
			}
			$this->success("创建成功!");			
		}
		else
		{
			$this->error($model->getError());
		}
    }
	public function currmas_edit()
	{
		$map = array();
        $map["where"]["id"] = $_GET["id"];

        $model= M("Currmas");
        $mydata = $model->find($map);
		$this->assign("mydata",$mydata);		
		$this->display();
    }
	public function currmas_edit_save()
	{
		$model = D("Currmas");
		$this->assign("jumpUrl",U('Finance/currmas_list'));
		if ($model->create())
		{
			$model->diyinfo=serialize($_POST['diyinfo']);
			$model->save(); // 保存数据
			if($_POST['flag']=='Y')
			{
				$data['flag']='N';
				$model->where('id not in ('.$_POST['id'].')')->save($data);
			}
			$this->success("保存成功!");
		}
		else
		{
			$this->error($model->getError());
		}
    }
	public function currmas_del()
	{
		$model = M("Currmas");
		$this->assign("jumpUrl",U('Finance/currmas_list'));
		$model->where("id in (".$_GET["id"].")")->delete(); // 删除
		if ($model)
		{
			$this->success("删除成功!");
		}
		else
		{
			$this->error($model->getError());
		}
    }
	public function currmas_status_to_y()
	{
		$model = M("Currmas");
		$this->assign("jumpUrl",U('Finance/currmas_list'));
		$data = array('status_flg'=>'Y');
		$model->where("id in (".$_GET["id"].")")->setField($data);
		if ($model)
		{
			$this->success("启用成功!");			
		}
		else
		{
			$this->error($model->getError());
		}
    }
	public function currmas_status_to_n()
	{
		$model = M("Currmas");
		$this->assign("jumpUrl",U('Finance/currmas_list'));
		$data = array('status_flg'=>'N');
		$model->where("id in (".$_GET["id"].")")->setField($data);
		if ($model)
		{
			$this->success("禁用成功!");			
		}
		else
		{
			$this->error($model->getError());
		}
    }
	public function currmas_popup()
	{
		$objcode=$_GET['objcode'];
		$objrate=$_GET['objrate'];
		$callback=$_GET['callback'];
		$this->assign("objcode",$objcode);
		$this->assign("objrate",$objrate);
		$this->assign("callback",$callback);
		
		$datalist = M("Currmas")->where("status_flg in ('Y','N')") -> order("flag desc,status_flg asc,orderid asc")->select();
		$this->assign("datalist",$datalist);
		$this->display();
    }
	
	/*  会计期间 */
	public function fiscalyp_list()
	{
		check_system();
		
		import("ORG.Util.Page"); // 导入分页类
		$model = M("Fiscalyp");
		
		$count      = $model->count(); // 查询满足要求的总记录数
		$Page       = new Page($count,12); //(int)C('LIST_PAGESIZE')==''?'12':C('LIST_PAGESIZE')); // 实例化分页类传入总记录数和每页显示的记录数 
		$show       = $Page->show(); // 分页显示输出
		
		$datalist = $model -> order("f_year desc,f_period desc")->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign("datalist",$datalist);
		$this->assign('page',$show); // 赋值分页输出
		
		if($count)
		{
			$max = $model->getField('max(f_year)');
			$fyear=(int)$max+1;
		}
		else
		{
			$fyear=(int)date('Y')-1;
		}
		$this->assign('fyear',$fyear);
		$this->display();
	}
	
	public function fiscalyp_add()
	{
		$fyear = $_GET['fyear'];
		if(!$fyear)
		{
			$this->error('参数错误');
			exit;
		}
		for($a=1;$a<=12;$a++)
		{
			$data[$a-1]['f_year']=$fyear;
			$data[$a-1]['f_period']=$a;			
			$data[$a-1]['title']=$fyear.'年'.$a.'月';
			$data[$a-1]['flag']='';
			$data[$a-1]['diyinfo']='';
			$data[$a-1]['posttime']=time();
			$data[$a-1]['status_flg']='0';
		}
		$model = M("Fiscalyp");
		$fiscalyp = $model->addAll($data);
		if($fiscalyp)
		{
			$this->success('创建成功');
		}
		else
		{
			$this->error($model->getError());
		}
	}
	
	public function fiscalyp_status_to_0()
	{
		$model = M("Fiscalyp");
		$this->assign("jumpUrl",U('Finance/fiscalyp_list'));
		$data = array('status_flg'=>'0');
		$model->where("id in (".$_GET["id"].")")->setField($data);
		if ($model)
		{
			$this->success("操作成功!");			
		}
		else
		{
			$this->error($model->getError());
		}
    }
	public function fiscalyp_status_to_1()
	{
		$model = M("Fiscalyp");
		$this->assign("jumpUrl",U('Finance/fiscalyp_list'));
		$data = array('status_flg'=>'1');
		$model->where("id in (".$_GET["id"].")")->setField($data);
		if ($model)
		{
			$this->success("操作成功!");			
		}
		else
		{
			$this->error($model->getError());
		}
    }
	public function fiscalyp_status_to_2()
	{
		$model = M("Fiscalyp");
		$this->assign("jumpUrl",U('Finance/fiscalyp_list'));
		$data = array('status_flg'=>'2');
		$model->where("id in (".$_GET["id"].")")->setField($data);
		if ($model)
		{
			$this->success("操作成功!");			
		}
		else
		{
			$this->error($model->getError());
		}
    }
	
	public function fiscalyp_check($fadate,$lv=2,$ajax=false)
	{
		return fiscalyp_check_common($fadate,$lv,$ajax);
	}
	
	
	/* 会计科目 */
	
	public function faccmas_list()
	{
		$model=M("Faccmas");
		$pid=$_REQUEST['pid'];
		$keywords=$_REQUEST['keywords'];
		if(!$pid) $pid=$model->where('parentid=0')->getField("min(id)");
		$this->assign("pid",$pid);
		$this->assign("keywords",$keywords);
		
		$datalist = $model
					-> field("id,parentid,parentstr,code,title,note,orderid,posttime,status_flg,diyinfo,concat(parentstr,'',id) as bpath") 
					-> where("(id=$pid or parentid=$pid or parentstr like '%,$pid,%') and (code like '%$keywords%' or title like '%$keywords%')")
					-> order("code,bpath asc")
					-> select();
		foreach($datalist as $key=>$value)
		{
			$datalist[$key]['count'] = count(explode(',',$value['parentstr']));
		}
		$this->assign("datalist",$datalist);
		
		$classlist=$model->where('parentid=0')->order('code asc')->select();
		$this->assign("classlist",$classlist);		
		
		$this->display();
    }
	public function faccmas_add()
	{		
		$pid=$_GET['pid'];
		if(!$pid) $pid=0;
		$this->get_faccmas_list();
		$this->assign("parentid",$pid);
		$orderid=M("Faccmas")->getField("max(orderid)+1");
		$this->assign("orderid",$orderid==null?1:$orderid);
		$this->display();
    }
	public function faccmas_add_save()
	{
		$model = D("Faccmas");
		$this->assign("jumpUrl",U('Finance/faccmas_list'));
		if ($model->create())
		{			
			$model->posttime=time();
			$model->diyinfo=serialize($_POST['diyinfo']);
			$dataid=$model->add();
			
			$data = array('parentstr'=>$this->get_faccmas_parentstr($dataid,$_POST['parentid']));
			$model->where("id=$dataid")->setField($data);
			
			$this->success("创建成功!");			
		}
		else
		{
			$this->error($model->getError());
		}
    }
	public function faccmas_edit()
	{
		$map = array();
        $map["where"]["id"] = $_GET["id"];

        $model= M("Faccmas");
        $mydata = $model->find($map);
		$this->assign("mydata",$mydata);
		$this->get_faccmas_list();
		$this->display();
    }
	public function faccmas_edit_save()
	{
		$model = D("Faccmas");
		$this->assign("jumpUrl",U('Finance/faccmas_list'));
		if ($model->create())
		{
			$model->diyinfo=serialize($_POST['diyinfo']);
			$model->save(); // 保存数据
			
			if($_POST['status_flg']=="N")
			{
				//当禁用类别时，自动禁用下级所有类别
				$data = array('status_flg'=>'N');
				$model->where("parentid=".$_POST['id']." or parentstr like '%,".$_POST['id'].",%'")->setField($data);
			}
			$this->set_faccmas_parentstr($_POST['id'],$_POST['parentid']);
			
			$this->success("保存成功!");			
		}
		else
		{
			$this->error($model->getError());
		}
    }
	public function faccmas_del()
	{
		$model = M("Faccmas");
		$this->assign("jumpUrl",U('Finance/faccmas_list'));	
		$data = array('status_flg'=>'N');		
		//$model->where("id in (".$_GET["id"].")")->delete(); // 删除
		$model->where("id in (".$_GET["id"].")")->setField($data); //禁用
		if ($model)
		{
			$this->success("禁用成功!");
		}
		else
		{
			$this->error($model->getError());
		}
    }
	public function get_faccmas_parentstr($cid,$pid=0)
	{
		if($pid==0)
		{
			return ',0,';
		}
		else
		{
			return M("Faccmas")->where("id=$pid")->getField("parentstr").$pid.",";
		}
	}
	
	public function set_faccmas_parentstr($id,$pid=0,$pstr='')
	{
		
		//获取当前parentstr
		if($pstr == '')
		{
			$parstr = $this->get_faccmas_parentstr($id,$pid);
		}
		else
		{
			$parstr = $pstr.$pid.',';
		}
			
		//更新信息表（当前级别）
		$data = array('parentid'=>$pid,'parentstr'=>$parstr);
		M("Faccmas")->where("id=$id")->setField($data);


		//获取当前ID下所有子ID
		$arrNav = M("Faccmas")->where("parentid=$id")->select();
		foreach($arrNav as $row)
		{
			//传递下级参数,继续更新
			$this->set_faccmas_parentstr($row['id'], $row['parentid'], $parstr);
		}

	}
	
	public function get_faccmas_list($listname='listlist')
	{
		$datalist = M("Faccmas")->field("id,parentid,parentstr,code,title,orderid,status_flg,concat(parentstr,'',code) as bpath") ->where("status_flg='Y'") -> order("bpath asc")->select();
		foreach($datalist as $key=>$value)
		{
			$datalist[$key]['count'] = count(explode(',',$value['parentstr']));
		}
		$this->assign($listname,$datalist);
	}
	public function faccmas_popup()
	{
		$objid=$_REQUEST['objid'];
		$objcode=$_REQUEST['objcode'];
		$objtitle=$_REQUEST['objtitle'];
		$this->assign("objid",$objid);
		$this->assign("objcode",$objcode);
		$this->assign("objtitle",$objtitle);
		
		$model=M("Faccmas");
		$pid=$_REQUEST['pid'];
		$keywords=$_REQUEST['keywords'];
		if(!$pid) $pid=0;
		$this->assign("pid",$pid);
		$this->assign("keywords",$keywords);
		
		$datalist = $model
					-> field("id,parentid,parentstr,code,title,note,orderid,posttime,status_flg,diyinfo,concat(parentstr,'',id) as bpath") 
					-> where("(id=$pid or parentid=$pid or parentstr like '%,$pid,%') and (code like '$keywords%' or title like '%$keywords%')")
					-> order("code,bpath asc")
					-> select();
		foreach($datalist as $key=>$value)
		{
			$datalist[$key]['count'] = count(explode(',',$value['parentstr']));
		}
		$this->assign("datalist",$datalist);
		
		$classlist=$model->where('parentid=0')->order('code asc')->select();
		$this->assign("classlist",$classlist);
		
		
		$this->display();
		
    }
	
	
	/* 默认科目 */
	
	public function faccdefault_list()
	{
		$datalist = D("Faccdefault")->relation(true) -> order("status_flg asc,orderid asc")->select();
		$this->assign("datalist",$datalist);
		$this->display();
    }
	public function faccdefault_add()
	{		
		$orderid=M("Faccdefault")->getField("max(orderid)+1");
		$this->assign("orderid",$orderid==null?1:$orderid);
		$this->display();
    }
	public function faccdefault_add_save()
	{
		$model = D("Faccdefault");
		$this->assign("jumpUrl",U('Finance/faccdefault_list'));
		if ($model->create())
		{			
			$model->posttime=time();
			$classid=$model->add();

			$this->success("创建成功!");			
		}
		else
		{
			$this->error($model->getError());
		}
    }
	public function faccdefault_edit()
	{
		$map = array();
        $map["where"]["id"] = $_GET["id"];

        $model= D("Faccdefault");
        $mydata = $model->relation(true)->find($map);
		$this->assign("mydata",$mydata);		
		$this->display();
    }
	public function faccdefault_edit_save()
	{
		$model = D("Faccdefault");
		$this->assign("jumpUrl",U('Finance/faccdefault_list'));
		if ($model->create())
		{
			$model->save(); // 保存数据
			$this->success("保存成功!");
		}
		else
		{
			$this->error($model->getError());
		}
    }
	public function faccdefault_del()
	{
		$model = M("Faccdefault");
		$this->assign("jumpUrl",U('Finance/faccdefault_list'));
		$model->where("id in (".$_GET["id"].")")->delete(); // 删除
		if ($model)
		{
			$this->success("删除成功!");
		}
		else
		{
			$this->error($model->getError());
		}
    }
	public function faccdefault_status_to_y()
	{
		$model = M("Faccdefault");
		$this->assign("jumpUrl",U('Finance/faccdefault_list'));
		$data = array('status_flg'=>'Y');
		$model->where("id in (".$_GET["id"].")")->setField($data);
		if ($model)
		{
			$this->success("启用成功!");			
		}
		else
		{
			$this->error($model->getError());
		}
    }
	public function faccdefault_status_to_n()
	{
		$model = M("Faccdefault");
		$this->assign("jumpUrl",U('Finance/faccdefault_list'));
		$data = array('status_flg'=>'N');
		$model->where("id in (".$_GET["id"].")")->setField($data);
		if ($model)
		{
			$this->success("禁用成功!");			
		}
		else
		{
			$this->error($model->getError());
		}
    }
	
	/* 总账凭证 */
	
	public function vou_list()
	{
	
		$s_status_flg = $_REQUEST['s_status_flg'];
		if(!$s_status_flg) $s_status_flg='%%';
		$keywords = $_REQUEST['keywords'];
		import("ORG.Util.Page"); // 导入分页类
		
		$model=D("VoumasView");
		$strwhere="Voumas.status_flg like '$s_status_flg'";
		if($keywords){$strwhere.=" and (Voumas.vouno like '%$keywords%' or Voumas.remark like '%$keywords%')";}		
		
		$count      = $model->where($strwhere)->count(); // 查询满足要求的总记录数
		$Page       = new Page($count,(int)C('LIST_PAGESIZE')==''?'10':C('LIST_PAGESIZE')); // 实例化分页类传入总记录数和每页显示的记录数 
		$Page->parameter   .=   "&s_status_flg=".urlencode($s_status_flg);   //传递查询条件
		$Page->parameter   .=   "&keywords=".urlencode($keywords);
		$show       = $Page->show(); // 分页显示输出
		
		$datalist = $model->where($strwhere) -> order("id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign("datalist",$datalist);
		$this->assign('page',$show); // 赋值分页输出
		
		$this->assign('s_status_flg',$s_status_flg);
		$this->assign('keywords',$keywords);
		
		$this->display();
    }
	
	public function vou_add()
	{		
		$currmas = M('Currmas')->where("flag='Y' and status_flg='Y'")->find();
		$this->assign("currmas",$currmas);
		$this->assign("fadate",date('Y-m-d'));
		$this->display();
    }
	
	public function vou_add_save()
	{		
		//var_dump($_POST['vouitem']);
		$model_mas = D("Voumas");
		$model_item = D("Vouitem");
		$model_mas->startTrans();	
		
		if ($model_mas->create())
		{			
			$model_mas->fadate=strtotime($_POST['fadate']);
			$model_mas->vouno = vouno_create(strtotime($_POST['fadate']));
			$model_mas->createtime=time();
			$model_mas->creater=$_SESSION[C('USER_AUTH_KEY')];
			$newid=$model_mas->add();
			
			$itmp = 0;
			foreach($_POST['vouitem'] as $item)
			{
				if($item['acc_code'] && ($item['curr_dr'] || $item['curr_cr']))
				{
					$data[$itmp]['masid']=$newid;
					$data[$itmp]['acc_code']=$item['acc_code'];
					$data[$itmp]['acc_title']=$item['acc_title'];
					$data[$itmp]['customer_id']=$item['customer_id'];
					$data[$itmp]['supplier_id']=$item['supplier_id'];
					$data[$itmp]['curr_code']=$item['curr_code'];
					$data[$itmp]['curr_rate']=$item['curr_rate'];
					$data[$itmp]['curr_dr']=get_round($item['curr_dr']);
					$data[$itmp]['dr']=get_round((double)$item['curr_dr']*(double)$item['curr_rate']);
					$data[$itmp]['curr_cr']=get_round($item['curr_cr']);
					$data[$itmp]['cr']=get_round((double)$item['curr_cr']*(double)$item['curr_rate']);
					$data[$itmp]['curr_open_amount']=get_round($item['curr_dr']==''?$item['curr_cr']:$item['curr_dr']);
					$data[$itmp]['open_amount']=get_round($item['dr']==''?(double)$item['curr_cr']*(double)$item['curr_rate']:(double)$item['curr_dr']*(double)$item['curr_rate']);
					$data[$itmp]['refid']=0;
					$itmp += 1;
				}
			}
			$item_flg = true;
			if($data)
			{
				$item_flg = $model_item->addAll($data);
			}
			if($newid && $item_flg)
			{
				$model_mas->commit();
				$this->assign("jumpUrl",U('Finance/vou_edit?id='.$newid));
				$this->success("操作已完成!");
			}
			else
			{
				$model_mas->rollback();
				$this->error('操作时发生错误。');
			}
						
		}
		else
		{
			$model_mas->rollback();
			$this->error($model_mas->getError());
		}
    }
	
	public function vou_edit()
	{		
		$map = array();
        $map["where"]["id"] = $_GET["id"];

        $model= D("VoumasView");
        $mydata = $model->find($map);
		$this->assign("mydata",$mydata);
		
		$model_item= D("VouitemView");
        $mydata_item = $model_item->where("masid = ".$_GET["id"])->select();
		$this->assign("mydata_item",$mydata_item);

		$item_num = count($mydata_item);
		$this->assign("item_num",$item_num);
		
		$currmas = M('Currmas')->where("flag='Y' and status_flg='Y'")->find();
		$this->assign("currmas",$currmas);
		
		$this->assign("fadate_write_off",date('Y-m-d'));
		
		$this->display();
    }
	
	public function vou_edit_save()
	{		
		if(!$this->vou_check_status($_REQUEST['id'],"'A','E'"))
		{
			$this->error('凭证状态要求为【活动中】');
			exit;
		}
		
		$model_mas = D("Voumas");
		$model_item = D("Vouitem");
		$model_mas->startTrans();
		
		if ($model_mas->create())
		{			
			$model_mas->fadate=strtotime($_POST['fadate']);
			$vouid = $_POST['id'];
			$model_mas->save();
			$delid=$model_item->where('masid='.$vouid)->delete();
			$itmp = 0;
			foreach($_POST['vouitem'] as $item)
			{
				if($item['acc_code'] && ($item['curr_dr'] || $item['curr_cr']))
				{
					$data[$itmp]['masid']=$vouid;
					$data[$itmp]['acc_code']=$item['acc_code'];
					$data[$itmp]['acc_title']=$item['acc_title'];
					$data[$itmp]['customer_id']=$item['customer_id'];
					$data[$itmp]['supplier_id']=$item['supplier_id'];
					$data[$itmp]['curr_code']=$item['curr_code'];
					$data[$itmp]['curr_rate']=$item['curr_rate'];
					$data[$itmp]['curr_dr']=get_round($item['curr_dr']);
					$data[$itmp]['dr']=get_round((double)$item['curr_dr']*(double)$item['curr_rate']);
					$data[$itmp]['curr_cr']=get_round($item['curr_cr']);
					$data[$itmp]['cr']=get_round((double)$item['curr_cr']*(double)$item['curr_rate']);
					$data[$itmp]['curr_open_amount']=get_round($item['curr_dr']==''?$item['curr_cr']:$item['curr_dr']);
					$data[$itmp]['open_amount']=get_round($item['dr']==''?(double)$item['curr_cr']*(double)$item['curr_rate']:(double)$item['curr_dr']*(double)$item['curr_rate']);
					$data[$itmp]['refid']=0;
					$itmp += 1;
				}
			}
			$item_flg = true;
			if($data)
			{
				$item_flg = $model_item->addAll($data);
			}

			if($vouid && $delid && $item_flg)
			{
				$model_mas->commit();
				$this->assign("jumpUrl",U('Finance/vou_edit?id='.$vouid));
				$this->success("操作已完成!");
			}
			else
			{
				$model_mas->rollback();
				$this->error('操作时发生错误。');
			}
						
		}
		else
		{
			$model_mas->rollback();
			$this->error($model_mas->getError());
		}
    }
	public function vou_save_post()
	{		
		if(!$this->vou_check_status($_REQUEST['id']))
		{
			$this->error('凭证状态要求为【活动中】');
			exit;
		}
		
		if(!fiscalyp_check_common($_REQUEST['fadate'],1))
		{
			$this->error('会计期间已关闭');
			exit;
		}
		
		$model_mas = D("Voumas");
		$model_item = D("Vouitem");
		$model_mas->startTrans();
		
		if ($model_mas->create())
		{			
			$model_mas->fadate=strtotime($_POST['fadate']);
			$model_mas->posttime=time();
			$model_mas->poster=$_SESSION[C('USER_AUTH_KEY')];
			$model_mas->status_flg='P';
			$vouid=$_POST['id'];
			$model_mas->save();
			$delid=$model_item->where('masid='.$vouid)->delete();
			$itmp = 0;
			$total_dr = 0;
			$total_cr = 0;
			foreach($_POST['vouitem'] as $item)
			{
				if($item['acc_code'] && ($item['curr_dr'] || $item['curr_cr']))
				{
					$data[$itmp]['masid']=$vouid;
					$data[$itmp]['acc_code']=$item['acc_code'];
					$data[$itmp]['acc_title']=$item['acc_title'];
					$data[$itmp]['customer_id']=$item['customer_id'];
					$data[$itmp]['supplier_id']=$item['supplier_id'];
					$data[$itmp]['curr_code']=$item['curr_code'];
					$data[$itmp]['curr_rate']=$item['curr_rate'];
					$data[$itmp]['curr_dr']=get_round($item['curr_dr']);
					$data[$itmp]['dr']=get_round((double)$item['curr_dr']*(double)$item['curr_rate']);
					$data[$itmp]['curr_cr']=get_round($item['curr_cr']);
					$data[$itmp]['cr']=get_round((double)$item['curr_cr']*(double)$item['curr_rate']);
					$data[$itmp]['curr_open_amount']=get_round($item['curr_dr']==''?$item['curr_cr']:$item['curr_dr']);
					$data[$itmp]['open_amount']=get_round($item['dr']==''?(double)$item['curr_cr']*(double)$item['curr_rate']:(double)$item['curr_dr']*(double)$item['curr_rate']);
					$data[$itmp]['refid']=0;
					$itmp += 1;
					$total_dr += $data[$itmp]['dr'];
					$total_cr += $data[$itmp]['cr'];
				}
			}
			$item_flg = true;
			if($data)
			{
				$item_flg = $model_item->addAll($data);
			}
			if($vouid && $delid && $item_flg && (get_round($total_dr)==get_round($total_cr)))
			{
				$model_mas->commit();
				$this->assign("jumpUrl",U('Finance/vou_edit?id='.$vouid));
				$this->success("操作已完成!");
			}
			else
			{
				$model_mas->rollback();
				$this->error('操作时发生错误。');
			}
						
		}
		else
		{
			$model_mas->rollback();
			$this->error($model_mas->getError());
		}
	}
	
	public function vou_post()
	{		
		if(!$this->vou_check_status($_REQUEST['id']))
		{
			$this->error('凭证状态要求为【活动中】');
			exit;
		}
		
		if(!fiscalyp_check_common($_REQUEST['fadate'],1))
		{
			$this->error('会计期间已关闭');
			exit;
		}
		
		$model_mas = D("Voumas");
		
		$data['id']=$_REQUEST['id'];
		$data['status_flg']='P';
		$data['posttime']=time();
		$data['poster']=$_SESSION[C('USER_AUTH_KEY')];
		
		$model_item =M("Vouitem");
		$balance = get_round($model_item->where("masid=".$data['id'])->sum("dr")) == get_round($model_item->where("masid=".$data['id'])->sum("cr")) ? true : false;
		if(!$balance)
		{
			$this->error('借贷不平衡');
			exit;
		}
		else if ($model_mas->save($data))
		{
			$this->assign("jumpUrl",U('Finance/vou_edit?id='.$_REQUEST['id']));
			$this->success("操作成功!");				
		}
		else
		{
			$this->error($model_mas->getError());
		}
    }
	
	public function vou_check_status($vouid,$vou_status="'A'")
	{
		$model_mas = M("Voumas");
		$where = "id in (".$vouid.") and status_flg in (".$vou_status.")";
		$chk = $model_mas->where($where)->find();
		if($chk)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	public function vou_status_to_a()
	{
		if($this->vou_check_status($_GET["id"],"'P'"))
		{
			$this->error('凭证已过账');
			exit;
		}
		
		$model = M("Voumas");
		$this->assign("jumpUrl",U('Finance/vou_list'));
		$data = array('status_flg'=>'A');
		$model->where("id in (".$_GET["id"].")")->setField($data);
		if ($model)
		{
			$this->success("启用成功!");			
		}
		else
		{
			$this->error($model->getError());
		}
    }
	
	public function vou_status_to_c()
	{
		if($this->vou_check_status($_GET["id"],"'P'"))
		{
			$this->error('凭证已过账');
			exit;
		}
		
		$model = M("Voumas");
		$this->assign("jumpUrl",U('Finance/vou_list'));
		$data = array('status_flg'=>'C');
		$model->where("id in (".$_GET["id"].")")->setField($data);
		if ($model)
		{
			$this->success("取消成功!");			
		}
		else
		{
			$this->error($model->getError());
		}
    }
	
	public function vou_write_off()
	{			
		if(!$this->vou_check_status($_REQUEST['id'],"'P'"))
		{
			$this->error('凭证状态要求为【已过账】');
			exit;
		}
		
		$model_mas = M("Voumas");
		$model_item = M("Vouitem");
		$model_mas->startTrans();
		
		$ori_id = $_GET['id'];
		$ori_mas = $model_mas->find($ori_id);
		
		if ($ori_mas)
		{			
			$data_mas['fadate'] = strtotime($_GET['fadate']);
			$data_mas['refcode'] = 'VOUMAS';
			$data_mas['refid'] = $ori_mas['id'];
			$data_mas['vouno'] = vouno_create(strtotime($_GET['fadate']));
			$data_mas['remark'] = '红字#'.$ori_mas['vouno'].'#'.$ori_mas['remark'];
			$data_mas['createtime'] = time();
			$data_mas['creater'] = $_SESSION[C('USER_AUTH_KEY')];
			$data_mas['status_flg'] = 'A';
			
			//var_dump($data_mas);

			$newid = $model_mas->data($data_mas)->add();
			$ori_item = $model_item->where('masid='.$ori_id)->order('id asc')->select();
			$itmp = 0;
			foreach($ori_item as $item)
			{
				if($item['acc_code'] && ($item['curr_dr'] || $item['curr_cr']))
				{
					$data[$itmp]['masid']=$newid;
					$data[$itmp]['acc_code']=$item['acc_code'];
					$data[$itmp]['acc_title']=$item['acc_title'];
					$data[$itmp]['customer_id']=$item['customer_id'];
					$data[$itmp]['supplier_id']=$item['supplier_id'];
					$data[$itmp]['curr_code']=$item['curr_code'];
					$data[$itmp]['curr_rate']=$item['curr_rate'];
					$data[$itmp]['curr_dr']=$item['curr_cr'];
					$data[$itmp]['dr']=$item['cr'];
					$data[$itmp]['curr_cr']=$item['curr_dr'];
					$data[$itmp]['cr']=$item['dr'];
					$data[$itmp]['curr_open_amount']=$item['curr_dr']==0?$item['curr_cr']:$item['curr_dr'];
					$data[$itmp]['open_amount']=$item['dr']==0?$item['cr']:$item['dr'];
					$data[$itmp]['refid']=0;
					$itmp += 1;
				}
			}
			
			//var_dump($data);
			
			$item_flg = true;
			if($data)
			{
				$item_flg = $model_item->addAll($data);
			}
			
			//var_dump($vouid);echo '<br><br>';
			//var_dump($delid);echo '<br><br>';
			//var_dump($item_flg);echo '<br><br>';
			
			if($newid && $item_flg)
			{
				$model_mas->commit();
				$this->assign("jumpUrl",U('Finance/vou_edit?id='.$newid));
				$this->success("操作已完成!");
			}
			else
			{
				//$this->assign("waitSecond",999);
				$model_mas->rollback();
				$this->error('操作时发生错误。');
			}
						
		}
		else
		{
			$model_mas->rollback();
			$this->error('原始凭证数据读取错误');
		}
    }
	//凭证被追踪
	public function vou_track()
	{		
		$map = array();
        $map["where"]["refcode"] = $_GET['refcode'];
		$map["where"]["refid"] = $_GET['refid'];

        $model= D("VoumasView");
        $mydata = $model->find($map);
		$this->assign("mydata",$mydata);
		
		$model_item= D("VouitemView");
        $mydata_item = $model_item->where("masid = ".$mydata['id'])->select();
		$this->assign("mydata_item",$mydata_item);

		$item_num = count($mydata_item);
		$this->assign("item_num",$item_num);
		
		$currmas = M('Currmas')->where("flag='Y' and status_flg='Y'")->find();
		$this->assign("currmas",$currmas);
		
		$this->assign("fadate_write_off",date('Y-m-d'));
		//C('SHOW_PAGE_TRACE',true);
		$this->display();
    }
	
	//往来收款和核销
	public function fa_checkin_list()
	{
	
		$s_status_flg = $_REQUEST['s_status_flg'];
		$keywords = $_REQUEST['keywords'];
		import("ORG.Util.Page"); // 导入分页类
		
		$model=D("FacheckmasView");
		$strwhere="Facheckmas.mas_code = 'ARCHKIN'";
		if($s_status_flg){$strwhere.=" and Facheckmas.status_flg like '$s_status_flg'";}
		if($keywords){$strwhere.=" and (Facheckmas.mas_no like '%$keywords%' or Facheckmas.remark like '%$keywords%' or Customer.title like '%$keywords%')";}	
		
		$count      = $model->where($strwhere)->count(); // 查询满足要求的总记录数
		$Page       = new Page($count,(int)C('LIST_PAGESIZE')==''?'10':C('LIST_PAGESIZE')); // 实例化分页类传入总记录数和每页显示的记录数 
		$Page->parameter   .=   "&s_status_flg=".urlencode($s_status_flg);   //传递查询条件
		$Page->parameter   .=   "&keywords=".urlencode($keywords);
		$show       = $Page->show(); // 分页显示输出
		
		$datalist = $model->where($strwhere) -> order("id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign("datalist",$datalist);
		$this->assign('page',$show); // 赋值分页输出
		
		$this->assign('s_status_flg',$s_status_flg);
		$this->assign('keywords',$keywords);
		
		//C('SHOW_PAGE_TRACE',true);
		$this->display();
    }
	public function fa_checkin_add()
	{		
		if($_POST['action_flg']=='CALLBACK')
		{
			$acc_info['acc_id']=$_POST['acc_id'];
			$acc_info['acc_title']=$_POST['acc_title'];
			$this->assign("acc_info",$acc_info);
			
			$currmas['code']=$_POST['curr_code'];
			$currmas['rate']=$_POST['curr_rate'];
			$this->assign("currmas",$currmas);
			
			$this->assign("fadate",$_POST['fadate']);
			
			$subQuery = D('Faccdefault')->relation(true)->field('acc_code')->where('code in (\'INV-AR\',\'PRECOLLECTED\') and status_flg=\'Y\'')->select(false);
			$model = D('VouitemView');
			$mydata_item = $model->where('customer_id='.$acc_info['acc_id'].' and curr_code=\''.$currmas['code'].'\' and (curr_open_amount!=0 or open_amount!=0) and acc_code in '.$subQuery)->order('id')->select();
			$this->assign("mydata_item",$mydata_item);
			
			$writeoff_item_num = count($mydata_item);
			$this->assign("writeoff_item_num",$writeoff_item_num);
		}
		else
		{
			$currmas = M('Currmas')->where("flag='Y' and status_flg='Y'")->find();
			$this->assign("currmas",$currmas);			
		
			$this->assign("fadate",date('Y-m-d'));
		}
		
		$faccdefault = D('Faccdefault')->relation(true)->where('code like \'BANK\' and status_flg=\'Y\'')->find();
		$this->assign("faccdefault",$faccdefault);
		
		$this->display();
    }
	
	public function fa_checkin_add_save()
	{		
		$model_mas = D("Facheckmas");
		$model_item = D("Facheckitem");
		$model_mas->startTrans();
		
		if ($model_mas->create())
		{			
			$model_mas->fadate=strtotime($_POST['fadate']);
			$model_mas->mas_no = facheck_masno_create($_POST['mas_code'],strtotime($_POST['fadate']));
			$model_mas->createtime=time();
			$model_mas->creater=$_SESSION[C('USER_AUTH_KEY')];
			$newid=$model_mas->add();
			
			$itmp = 0;
			foreach($_POST['checkitem'] as $item)
			{
				if($item['acc_code'] && $item['curr_dr'])
				{
					$data[$itmp]['masid']=$newid;
					$data[$itmp]['acc_code']=$item['acc_code'];
					$data[$itmp]['acc_title']=$item['acc_title'];
					$data[$itmp]['customer_id']=0;
					$data[$itmp]['supplier_id']=0;
					$data[$itmp]['curr_code']=$_POST['curr_code'];
					$data[$itmp]['curr_rate']=$_POST['curr_rate'];
					$data[$itmp]['curr_dr']=get_round($item['curr_dr']);
					$data[$itmp]['dr']=get_round((double)$item['curr_dr']*(double)$_POST['curr_rate']);
					$data[$itmp]['curr_cr']=0;
					$data[$itmp]['cr']=0;
					$data[$itmp]['curr_open_amount']=get_round($data[$itmp]['curr_dr']);
					$data[$itmp]['open_amount']=get_round($data[$itmp]['dr']);
					$data[$itmp]['refid']=0;
					$data[$itmp]['ref_remark']=$_POST['remark'];
					$itmp += 1;
				}
			}
			foreach($_POST['vouitem'] as $item)
			{
				if($item['writeoff']=='Y' && $item['acc_code'] && $item['curr_open_amount'])
				{
					$data[$itmp]['masid']=$newid;
					$data[$itmp]['acc_code']=$item['acc_code'];
					$data[$itmp]['acc_title']=$item['acc_title'];
					$data[$itmp]['customer_id']=$_POST['acc_id'];
					$data[$itmp]['supplier_id']=0;
					$data[$itmp]['curr_code']=$item['curr_code'];
					$data[$itmp]['curr_rate']=$item['curr_rate'];
					$data[$itmp]['curr_dr']=get_round($item['curr_dr']);
					$data[$itmp]['dr']=get_round($item['dr']);
					$data[$itmp]['curr_cr']=get_round($item['curr_cr']);
					$data[$itmp]['cr']=get_round($item['cr']);
					$data[$itmp]['curr_open_amount']=get_round($item['curr_open_amount']);
					$data[$itmp]['open_amount']=get_round((double)$item['curr_open_amount']*(double)$item['curr_rate']);
					$data[$itmp]['refid']=$item['detail_id'];
					$data[$itmp]['ref_remark']=$item['ref_remark'];
					$itmp += 1;
				}
			}
			
			$item_flg = true;
			if($data)
			{
				$item_flg = $model_item->addAll($data);
			}

			if($newid && $item_flg)
			{
				$model_mas->commit();
				$this->assign("jumpUrl",U('Finance/fa_checkin_edit?id='.$newid));
				$this->success("操作已完成!");
			}
			else
			{
				$model_mas->rollback();
				$this->error('操作时发生错误。');
			}
						
		}
		else
		{
			$model_mas->rollback();
			$this->error($model_mas->getError());
		}
    }
	
	public function fa_checkin_edit()
	{		
		$map = array();
        $map["where"]["id"] = $_GET["id"];

        $model= D("FacheckmasView");
        $mydata = $model->find($map);
		$this->assign("mydata",$mydata);
		
		$model_item= D("FacheckitemView");
        $mydata_item = $model_item->where("masid = ".$_GET["id"]." and refid=0")->select();
		$this->assign("mydata_item",$mydata_item);
		$item_num = count($mydata_item);
		$this->assign("item_num",$item_num);
		
		if($mydata['status_flg']=='A') //活动状态下，需要把可以核销的明细导出来，并与做单时的数据匹配
		{
			$subQuery = D('Faccdefault')->relation(true)->field('acc_code')->where('code in (\'INV-AR\',\'PRECOLLECTED\') and status_flg=\'Y\'')->select(false);
			$model_vou = D('VouitemView');
			$writeoff_item = $model_vou->where('customer_id='.$mydata['acc_id'].' and curr_code=\''.$mydata['curr_code'].'\' and (curr_open_amount!=0 or open_amount!=0) and acc_code in '.$subQuery)->order('id')->select();
			$writeoff_tmp1 = $model_item->where("masid = ".$_GET["id"]." and refid>0")->select();
			
			foreach($writeoff_tmp1 as $item)
			{
				$writeoff_tmp2[$item['refid']]['refid']=$item['refid'];
				$writeoff_tmp2[$item['refid']]['ref_remark']=$item['ref_remark'];
				$writeoff_tmp2[$item['refid']]['curr_writeoff_amount']=$item['curr_open_amount'];
				$writeoff_tmp2[$item['refid']]['writeoff_amount']=$item['open_amount'];
				$writeoff_tmp2[$item['refid']]['writeoff']='Y';
			}
			foreach($writeoff_item as $key=>$value)
			{
				if((double)$writeoff_tmp2[$value['id']]['refid'] > 0)
				{
					$writeoff_item[$key]['curr_writeoff_amount'] = (double)$writeoff_tmp2[$value['id']]['curr_writeoff_amount'] > (double)$value['curr_open_amount'] ? $value['curr_open_amount'] : $writeoff_tmp2[$value['id']]['curr_writeoff_amount'];
					$writeoff_item[$key]['writeoff_amount'] = (double)$writeoff_tmp2[$value['id']]['writeoff_amount'] > (double)$value['open_amount'] ? $value['open_amount'] : $writeoff_tmp2[$value['id']]['writeoff_amount'];
					$writeoff_item[$key]['writeoff'] = $writeoff_tmp2[$value['id']]['writeoff']=='Y' ? 'Y' : 'N';
					$writeoff_item[$key]['mas_remark'] = $writeoff_tmp2[$value['id']]['ref_remark']=='' ? $value['mas_remark'] : $writeoff_tmp2[$value['id']]['ref_remark'];
					$writeoff_item[$key]['refid'] = $writeoff_tmp2[$value['id']]['refid'];
				}
				else
				{
					$writeoff_item[$key]['curr_writeoff_amount'] = 0;
					$writeoff_item[$key]['writeoff_amount'] = 0;
					$writeoff_item[$key]['writeoff'] = 'N';
					$writeoff_item[$key]['mas_remark'] = $value['mas_remark'];
					$writeoff_item[$key]['refid'] = $value['id'];
				}
			}
			//var_dump($writeoff_item);
			$this->assign("writeoff_item",$writeoff_item);
			$writeoff_item_num = count($writeoff_item);
			$this->assign("writeoff_item_num",$writeoff_item_num);
		}
		else //不是活动状态，则直接读取做单时的数据
		{
			$writeoff_item = $model_item->where("masid = ".$_GET["id"]." and refid>0")->select();
			foreach($writeoff_item as $key=>$value)
			{
					$writeoff_item[$key]['curr_writeoff_amount'] = $value['curr_open_amount'];
					$writeoff_item[$key]['writeoff_amount'] = $value['open_amount'];
					$writeoff_item[$key]['writeoff'] = 'Y';
					$writeoff_item[$key]['mas_remark'] = $value['ref_remark'];
					
			}
			$this->assign("writeoff_item",$writeoff_item);
			$writeoff_item_num = count($writeoff_item);
			$this->assign("writeoff_item_num",$writeoff_item_num);
		}
		
		
		$currmas = M('Currmas')->where("flag='Y' and status_flg='Y'")->find();
		$this->assign("currmas",$currmas);
		
		$faccdefault = D('Faccdefault')->relation(true)->where('code like \'BANK\' and status_flg=\'Y\'')->find();
		$this->assign("faccdefault",$faccdefault);
		
		$this->display();
    }
	
	public function fa_checkin_edit_save()
	{		
		if(!$this->facheck_check_status($_REQUEST['id'],"'A','E'"))
		{
			$this->error('单据状态要求为【活动中】');
			exit;
		}
		
		$model_mas = D("Facheckmas");
		$model_item = D("Facheckitem");
		$model_mas->startTrans();
		
		if ($model_mas->create())
		{			
			$newid=$_POST['id'];
			$model_mas->fadate=strtotime($_POST['fadate']);			
			$model_mas->save();
			
			$delid = true;
			$itemcount = $model_item->where('masid='.$newid)->count();
			if($itemcount)$delid=$model_item->where('masid='.$newid)->delete();
			
			$itmp = 0;
			foreach($_POST['checkitem'] as $item)
			{
				if($item['acc_code'] && $item['curr_dr'])
				{
					$data[$itmp]['masid']=$newid;
					$data[$itmp]['acc_code']=$item['acc_code'];
					$data[$itmp]['acc_title']=$item['acc_title'];
					$data[$itmp]['customer_id']=0;
					$data[$itmp]['supplier_id']=0;
					$data[$itmp]['curr_code']=$_POST['curr_code'];
					$data[$itmp]['curr_rate']=$_POST['curr_rate'];
					$data[$itmp]['curr_dr']=get_round($item['curr_dr']);
					$data[$itmp]['dr']=get_round((double)$item['curr_dr']*(double)$_POST['curr_rate']);
					$data[$itmp]['curr_cr']=0;
					$data[$itmp]['cr']=0;
					$data[$itmp]['curr_open_amount']=get_round($data[$itmp]['curr_dr']);
					$data[$itmp]['open_amount']=get_round($data[$itmp]['dr']);
					$data[$itmp]['refid']=0;
					$data[$itmp]['ref_remark']=$_POST['remark'];
					$itmp += 1;
				}
			}
			foreach($_POST['vouitem'] as $item)
			{
				if($item['writeoff']=='Y' && $item['acc_code'] && $item['curr_open_amount'])
				{
					$data[$itmp]['masid']=$newid;
					$data[$itmp]['acc_code']=$item['acc_code'];
					$data[$itmp]['acc_title']=$item['acc_title'];
					$data[$itmp]['customer_id']=$_POST['acc_id'];
					$data[$itmp]['supplier_id']=0;
					$data[$itmp]['curr_code']=$item['curr_code'];
					$data[$itmp]['curr_rate']=$item['curr_rate'];
					$data[$itmp]['curr_dr']=get_round($item['curr_dr']);
					$data[$itmp]['dr']=get_round($item['dr']);
					$data[$itmp]['curr_cr']=get_round($item['curr_cr']);
					$data[$itmp]['cr']=get_round($item['cr']);
					$data[$itmp]['curr_open_amount']=get_round($item['curr_open_amount']);
					$data[$itmp]['open_amount']=get_round((double)$item['curr_open_amount']*(double)$item['curr_rate']);
					$data[$itmp]['refid']=$item['detail_id'];
					$data[$itmp]['ref_remark']=$item['ref_remark'];
					$itmp += 1;
				}
			}
			$item_flg = true;
			if($data)
			{
				$item_flg = $model_item->addAll($data);
			}
			if($newid && $delid && $item_flg)
			{
				$model_mas->commit();
				$this->assign("jumpUrl",U('Finance/fa_checkin_edit?id='.$newid));
				$this->success("操作已完成!");
			}
			else
			{
				$model_mas->rollback();
				$this->error('操作时发生错误。');
			}
						
		}
		else
		{
			$model_mas->rollback();
			$this->error($model_mas->getError());
		}
    }
	public function fa_checkin_save_post()
	{		
		if(!$this->facheck_check_status($_REQUEST['id']))
		{
			$this->error('单据状态要求为【活动中】');
			exit;
		}
		
		if(!fiscalyp_check_common($_REQUEST['fadate'],1))
		{
			$this->error('会计期间已关闭');
			exit;
		}
		
		$model_mas = D("Facheckmas");
		$model_item = D("Facheckitem");
		$model_mas->startTrans();
		
		if ($model_mas->create())
		{			
			$newid=$_POST['id'];
			$model_mas->fadate=strtotime($_POST['fadate']);
			$model_mas->posttime=time();
			$model_mas->poster=$_SESSION[C('USER_AUTH_KEY')];
			$model_mas->status_flg='P';
			
			$model_mas->save();
			
			$delid = true;
			$itemcount = $model_item->where('masid='.$newid)->count();
			if($itemcount)$delid=$model_item->where('masid='.$newid)->delete();
			
			//生成总账MAS
			$model_vou_mas = M('Voumas');
			$model_vou_item= M('Vouitem');
			
			$data_vou_mas['fadate']=strtotime($_POST['fadate']);
			$data_vou_mas['refcode']=$_POST['mas_code'];
			$data_vou_mas['refid']=$newid;
			$data_vou_mas['vouno']=vouno_create(strtotime($_POST['fadate']));
			$data_vou_mas['remark']='从'.$_POST['mas_code'].'#'.$_POST['mas_no'].'#'.$_POST['remark'];
			$data_vou_mas['createtime']=time();
			$data_vou_mas['creater']=$_SESSION[C('USER_AUTH_KEY')];
			$data_vou_mas['posttime']=time();
			$data_vou_mas['poster']=$_SESSION[C('USER_AUTH_KEY')];
			$data_vou_mas['status_flg']='P';
			$vouid=$model_vou_mas->data($data_vou_mas)->add();
			
			$itmp = 0;
			$total_dr_curr = 0;
			$total_dr = 0;
			$total_cr_curr = 0;
			$total_cr = 0;
			foreach($_POST['checkitem'] as $item)
			{
				if($item['acc_code'] && $item['curr_dr'])
				{
					$data[$itmp]['masid']=$newid;
					$data[$itmp]['acc_code']=$item['acc_code'];
					$data[$itmp]['acc_title']=$item['acc_title'];
					$data[$itmp]['customer_id']=0;
					$data[$itmp]['supplier_id']=0;
					$data[$itmp]['curr_code']=$_POST['curr_code'];
					$data[$itmp]['curr_rate']=$_POST['curr_rate'];
					$data[$itmp]['curr_dr']=get_round($item['curr_dr']);
					$data[$itmp]['dr']=get_round((double)$item['curr_dr']*(double)$_POST['curr_rate']);
					$data[$itmp]['curr_cr']=0;
					$data[$itmp]['cr']=0;
					$data[$itmp]['curr_open_amount']=get_round($data[$itmp]['curr_dr']);
					$data[$itmp]['open_amount']=get_round($data[$itmp]['dr']);
					$data[$itmp]['refid']=0;
					$data[$itmp]['ref_remark']=$_POST['remark'];
					
					//要生成新凭证的数据(正方向)(本次收款的数据)
					$vou_dtl[$itmp]['masid']=$vouid;
					$vou_dtl[$itmp]['acc_code']=$item['acc_code'];
					$vou_dtl[$itmp]['acc_title']=$item['acc_title'];
					$vou_dtl[$itmp]['customer_id']=0;
					$vou_dtl[$itmp]['supplier_id']=0;
					$vou_dtl[$itmp]['curr_code']=$_POST['curr_code'];
					$vou_dtl[$itmp]['curr_rate']=$_POST['curr_rate'];
					$vou_dtl[$itmp]['curr_dr']=get_round($item['curr_dr']);
					$vou_dtl[$itmp]['dr']=get_round((double)$item['curr_dr']*(double)$_POST['curr_rate']);
					$vou_dtl[$itmp]['curr_cr']=0;
					$vou_dtl[$itmp]['cr']=0;
					$vou_dtl[$itmp]['curr_open_amount']=0;
					$vou_dtl[$itmp]['open_amount']=0;
					$vou_dtl[$itmp]['refid']=0;
					$data[$itmp]['ref_remark']=$item['ref_remark'];
					
					$total_dr_curr += (double)$vou_dtl[$itmp]['curr_dr'];
					$total_dr      += (double)$vou_dtl[$itmp]['dr'];
					$total_cr_curr += (double)$vou_dtl[$itmp]['curr_cr'];
					$total_cr      += (double)$vou_dtl[$itmp]['cr'];
					
					$itmp += 1;
				}
			}
			foreach($_POST['vouitem'] as $item)
			{
				if($item['writeoff']=='Y' && $item['acc_code'] && $item['curr_open_amount'])
				{
					$data[$itmp]['masid']=$newid;
					$data[$itmp]['acc_code']=$item['acc_code'];
					$data[$itmp]['acc_title']=$item['acc_title'];
					$data[$itmp]['customer_id']=$_POST['acc_id'];
					$data[$itmp]['supplier_id']=0;
					$data[$itmp]['curr_code']=$item['curr_code'];
					$data[$itmp]['curr_rate']=$item['curr_rate'];
					$data[$itmp]['curr_dr']=get_round($item['curr_dr']);
					$data[$itmp]['dr']=get_round($item['dr']);
					$data[$itmp]['curr_cr']=get_round($item['curr_cr']);
					$data[$itmp]['cr']=get_round($item['cr']);
					$data[$itmp]['curr_open_amount']=get_round($item['curr_open_amount']);
					$data[$itmp]['open_amount']=get_round((double)$item['curr_open_amount']*(double)$item['curr_rate']);
					$data[$itmp]['refid']=$item['detail_id'];
					$data[$itmp]['ref_remark']=$item['ref_remark'];
					
					//要冲销并回写的数据
					$deduct_dtl[$itmp]['refid']=$item['detail_id'];
					$deduct_dtl[$itmp]['curr_open_amount']=$item['curr_open_amount'];
					$deduct_dtl[$itmp]['open_amount']=(double)$item['curr_open_amount']*(double)$item['curr_rate'];
				
					//要生成新凭证的数据(反方向)
					$vou_dtl[$itmp]['masid']=$vouid;
					$vou_dtl[$itmp]['acc_code']=$item['acc_code'];
					$vou_dtl[$itmp]['acc_title']=$item['acc_title'];
					$vou_dtl[$itmp]['customer_id']=$_POST['acc_id'];
					$vou_dtl[$itmp]['supplier_id']=0;
					$vou_dtl[$itmp]['curr_code']=$item['curr_code'];
					$vou_dtl[$itmp]['curr_rate']=$item['curr_rate'];
					$vou_dtl[$itmp]['curr_dr']=get_round((double)$item['curr_dr'] > 0 ? 0 : $item['curr_open_amount']);
					$vou_dtl[$itmp]['dr']=get_round((double)$item['dr'] > 0 ? 0 : (double)$item['curr_open_amount']*(double)$item['curr_rate']);
					$vou_dtl[$itmp]['curr_cr']=get_round((double)$item['curr_cr'] > 0 ? 0 : $item['curr_open_amount']);
					$vou_dtl[$itmp]['cr']=get_round((double)$item['cr'] > 0 ? 0 : (double)$item['curr_open_amount']*(double)$item['curr_rate']);
					$vou_dtl[$itmp]['curr_open_amount']=0;
					$vou_dtl[$itmp]['open_amount']=0;
					$vou_dtl[$itmp]['refid']=$item['detail_id'];
					
					$total_dr_curr += (double)$vou_dtl[$itmp]['curr_dr'];
					$total_dr      += (double)$vou_dtl[$itmp]['dr'];
					$total_cr_curr += (double)$vou_dtl[$itmp]['curr_cr'];
					$total_cr      += (double)$vou_dtl[$itmp]['cr'];
					
					$itmp += 1;
				}
			}
		
		//如果收款没有核销完，则记入预收款
		if($total_dr_curr != $total_cr_curr)
		{
			$faccdef = D('Faccdefault')->relation(true)->where('code = \'PRECOLLECTED\'')->find();
			if($faccdef)
			{
				$diff_amount = $total_dr_curr - $total_cr_curr; //差异金额
				
				$vou_dtl[$itmp]['masid']=$vouid;
				$vou_dtl[$itmp]['acc_code']=$faccdef['acc_code'];
				$vou_dtl[$itmp]['acc_title']=$faccdef['acc_title'];
				$vou_dtl[$itmp]['customer_id']=$_POST['acc_id'];
				$vou_dtl[$itmp]['supplier_id']=0;
				$vou_dtl[$itmp]['curr_code']=$_POST['curr_code'];
				$vou_dtl[$itmp]['curr_rate']=$_POST['curr_rate'];
				$vou_dtl[$itmp]['curr_dr']= get_round($diff_amount < 0 ? $diff_amount*-1 : 0);
				$vou_dtl[$itmp]['dr']=get_round($diff_amount < 0 ? $diff_amount*-1*(float)$_POST['curr_rate'] : 0);
				$vou_dtl[$itmp]['curr_cr']= get_round($diff_amount > 0 ? $diff_amount : 0);
				$vou_dtl[$itmp]['cr']=get_round($diff_amount > 0 ? $diff_amount*(float)$_POST['curr_rate'] : 0);
				$vou_dtl[$itmp]['curr_open_amount']=get_round($diff_amount > 0 ? $vou_dtl[$itmp]['curr_cr'] : $vou_dtl[$itmp]['curr_dr']);
				$vou_dtl[$itmp]['open_amount']=get_round($diff_amount > 0 ? $vou_dtl[$itmp]['cr'] : $vou_dtl[$itmp]['dr']);
				$vou_dtl[$itmp]['refid']=0;
				
				$total_dr_curr += (double)$vou_dtl[$itmp]['curr_dr'];
				$total_dr      += (double)$vou_dtl[$itmp]['dr'];
				$total_cr_curr += (double)$vou_dtl[$itmp]['curr_cr'];
				$total_cr      += (double)$vou_dtl[$itmp]['cr'];
				$itmp+=1;
			}
			else
			{
				$model_mas->rollback();
				$this->error("没有定义预收账款会计科目!");
			}
		}		
		//如果原币已平，但本位币不平，则记入损益
		if($total_dr != $total_cr)
		{
			$faccdef = D('Faccdefault')->relation(true)->where('code = \'EGOL\'')->find();
			//$fcurrmas = M('Currmas')->where('flag = \'Y\' and status_flg=\'Y\'')->find();
			if($faccdef)
			{
				$diff_amount = $total_dr - $total_cr; //差异金额
				
				$vou_dtl[$itmp]['masid']=$vouid;
				$vou_dtl[$itmp]['acc_code']=$faccdef['acc_code'];
				$vou_dtl[$itmp]['acc_title']=$faccdef['acc_title'];
				$vou_dtl[$itmp]['customer_id']=$_POST['acc_id'];
				$vou_dtl[$itmp]['supplier_id']=0;
				$vou_dtl[$itmp]['curr_code']=$_POST['curr_code'];
				$vou_dtl[$itmp]['curr_rate']=$_POST['curr_rate'];
				$vou_dtl[$itmp]['curr_dr']= 0;
				$vou_dtl[$itmp]['dr']=get_round($diff_amount < 0 ? $diff_amount*-1 : 0);
				$vou_dtl[$itmp]['curr_cr']= 0;
				$vou_dtl[$itmp]['cr']=get_round($diff_amount > 0 ? $diff_amount : 0);
				$vou_dtl[$itmp]['curr_open_amount']=0;
				$vou_dtl[$itmp]['open_amount']=0;
				$vou_dtl[$itmp]['refid']=0;
				
				$total_dr_curr += (double)$vou_dtl[$itmp]['curr_dr'];
				$total_dr      += (double)$vou_dtl[$itmp]['dr'];
				$total_cr_curr += (double)$vou_dtl[$itmp]['curr_cr'];
				$total_cr      += (double)$vou_dtl[$itmp]['cr'];
				$itmp+=1;
			}
			else
			{
				$model_mas->rollback();
				$this->error("没有定义财务损益会计科目，或没有设置本位币!");
			}
		}
        $total_dr_curr = sprintf("%.2f", $total_dr_curr);
        $total_cr_curr = sprintf("%.2f", $total_cr_curr);
        $total_dr = sprintf("%.2f", $total_dr);
        $total_cr = sprintf("%.2f", $total_cr);
		if($total_dr_curr!=$total_cr_curr || $total_dr!=$total_cr)
		{
				$model_mas->rollback();
				$this->error("借贷不平衡!");
		}
		
		
			$item_flg = true;
			if($data)
			{
				$item_flg = $model_item->addAll($data);
			}
			
			//生成总账ITEM
			// 核销，回写原始记录的open amount
			$deduct_flg = true;
			if($deduct_dtl)
			{
				$deduct_flg = deduct_gl($deduct_dtl);
				if($deduct_flg['flg']===false)
				{
					$model_mas->rollback();
					$this->error($deduct_flg['msg']);
				}
			}
		
			//写入新分录
			$vou_item_flg = true;
			if($vou_dtl)
			{
				$vou_item_flg=$model_vou_item->addAll($vou_dtl);
			}
			
			
			if($newid && $delid && $item_flg && $vouid && $vou_item_flg)
			{
				$model_mas->commit();
				$this->assign("jumpUrl",U('Finance/fa_checkin_edit?id='.$newid));
				$this->success("操作已完成!");
			}
			else
			{
				$model_mas->rollback();
				$this->error('操作时发生错误。');
			}
						
		}
		else
		{
			$model_mas->rollback();
			$this->error($model_mas->getError());
		}
	}
	
	public function fa_checkin_post()
	{		
		if(!$this->facheck_check_status($_REQUEST['id']))
		{
			$this->error('单据状态要求为【活动中】');
			exit;
		}
		
		$model_mas = D("Facheckmas");
		$model_item = D("Facheckitem");
		$model_mas->startTrans();
		
		$ori_id = $_REQUEST['id'];
		$ori_mas = $model_mas->find($ori_id);
		$ori_item = $model_item->where('masid='.$ori_id)->select();
		
		if(!fiscalyp_check_common($ori_mas['fadate'],1))
		{
			$this->error('会计期间已关闭');
			exit;
		}
		
		$data['id']=$_REQUEST['id'];
		$data['status_flg']='P';
		$data['posttime']=time();
		$data['poster']=$_SESSION[C('USER_AUTH_KEY')];
		
		$facheckmasid=$model_mas->save($data);

			
		//生成总账
			$model_vou_mas = M('Voumas');
			$model_vou_item= M('Vouitem');
			
			$data_vou_mas['fadate']=$ori_mas['fadate'];
			$data_vou_mas['refcode']=$ori_mas['mas_code'];
			$data_vou_mas['refid']=$ori_id;
			$data_vou_mas['vouno']=vouno_create($ori_mas['fadate']);
			$data_vou_mas['remark']='从'.$ori_mas['mas_code'].'#'.$ori_mas['mas_no'].'#'.$ori_mas['remark'];
			$data_vou_mas['createtime']=time();
			$data_vou_mas['creater']=$_SESSION[C('USER_AUTH_KEY')];
			$data_vou_mas['posttime']=time();
			$data_vou_mas['poster']=$_SESSION[C('USER_AUTH_KEY')];
			$data_vou_mas['status_flg']='P';
			$vouid=$model_vou_mas->data($data_vou_mas)->add();
			
		$itmp = 0;
		$total_dr_curr = 0;
		$total_dr = 0;
		$total_cr_curr = 0;
		$total_cr = 0;
		foreach($ori_item as $item)
		{
			if($item['refid'])
			{
				//要冲销并回写的数据
				$deduct_dtl[$itmp]['refid']=$item['refid'];
				$deduct_dtl[$itmp]['curr_open_amount']=$item['curr_open_amount'];
				$deduct_dtl[$itmp]['open_amount']=$item['open_amount'];
				
				//要生成新凭证的数据(反方向)
				$vou_dtl[$itmp]['masid']=$vouid;
				$vou_dtl[$itmp]['acc_code']=$item['acc_code'];
				$vou_dtl[$itmp]['acc_title']=$item['acc_title'];
				$vou_dtl[$itmp]['customer_id']=$item['customer_id'];
				$vou_dtl[$itmp]['supplier_id']=$item['supplier_id'];
				$vou_dtl[$itmp]['curr_code']=$item['curr_code'];
				$vou_dtl[$itmp]['curr_rate']=$item['curr_rate'];
				$vou_dtl[$itmp]['curr_dr']=get_round((double)$item['curr_dr'] > 0 ? 0 : $item['curr_open_amount']);
				$vou_dtl[$itmp]['dr']=get_round((double)$item['dr'] > 0 ? 0 : $item['open_amount']);
				$vou_dtl[$itmp]['curr_cr']=get_round((double)$item['curr_cr'] > 0 ? 0 : $item['curr_open_amount']);
				$vou_dtl[$itmp]['cr']=get_round((double)$item['cr'] > 0 ? 0 : $item['open_amount']);
				$vou_dtl[$itmp]['curr_open_amount']=0;
				$vou_dtl[$itmp]['open_amount']=0;
				$vou_dtl[$itmp]['refid']=$item['refid'];
				
			}
			else
			{
				//要生成新凭证的数据(正方向)(本次收款的数据)
				$vou_dtl[$itmp]['masid']=$vouid;
				$vou_dtl[$itmp]['acc_code']=$item['acc_code'];
				$vou_dtl[$itmp]['acc_title']=$item['acc_title'];
				$vou_dtl[$itmp]['customer_id']=$item['customer_id'];
				$vou_dtl[$itmp]['supplier_id']=$item['supplier_id'];
				$vou_dtl[$itmp]['curr_code']=$item['curr_code'];
				$vou_dtl[$itmp]['curr_rate']=$item['curr_rate'];
				$vou_dtl[$itmp]['curr_dr']=get_round($item['curr_dr']);
				$vou_dtl[$itmp]['dr']=get_round($item['dr']);
				$vou_dtl[$itmp]['curr_cr']=get_round($item['curr_cr']);
				$vou_dtl[$itmp]['cr']=get_round($item['cr']);
				$vou_dtl[$itmp]['curr_open_amount']=0;
				$vou_dtl[$itmp]['open_amount']=0;
				$vou_dtl[$itmp]['refid']=0;
			}
			$total_dr_curr += (double)$vou_dtl[$itmp]['curr_dr'];
			$total_dr      += (double)$vou_dtl[$itmp]['dr'];
			$total_cr_curr += (double)$vou_dtl[$itmp]['curr_cr'];
			$total_cr      += (double)$vou_dtl[$itmp]['cr'];
			$itmp+=1;
		}
		//如果收款没有核销完，则记入预收款
		if($total_dr_curr != $total_cr_curr)
		{
			$faccdef = D('Faccdefault')->relation(true)->where('code = \'PRECOLLECTED\'')->find();
			if($faccdef)
			{
				$diff_amount = $total_dr_curr - $total_cr_curr; //差异金额
				
				$vou_dtl[$itmp]['masid']=$vouid;
				$vou_dtl[$itmp]['acc_code']=$faccdef['acc_code'];
				$vou_dtl[$itmp]['acc_title']=$faccdef['acc_title'];
				$vou_dtl[$itmp]['customer_id']=$ori_mas['acc_id'];
				$vou_dtl[$itmp]['supplier_id']=0;
				$vou_dtl[$itmp]['curr_code']=$ori_mas['curr_code'];
				$vou_dtl[$itmp]['curr_rate']=$ori_mas['curr_rate'];
				$vou_dtl[$itmp]['curr_dr']= get_round($diff_amount < 0 ? $diff_amount*-1 : 0);
				$vou_dtl[$itmp]['dr']=get_round($diff_amount < 0 ? $diff_amount*-1*(float)$ori_mas['curr_rate'] : 0);
				$vou_dtl[$itmp]['curr_cr']= get_round($diff_amount > 0 ? $diff_amount : 0);
				$vou_dtl[$itmp]['cr']=get_round($diff_amount > 0 ? $diff_amount*(float)$ori_mas['curr_rate'] : 0);
				$vou_dtl[$itmp]['curr_open_amount']=get_round($diff_amount > 0 ? $vou_dtl[$itmp]['curr_cr'] : $vou_dtl[$itmp]['curr_dr']);
				$vou_dtl[$itmp]['open_amount']=get_round($diff_amount > 0 ? $vou_dtl[$itmp]['cr'] : $vou_dtl[$itmp]['dr']);
				$vou_dtl[$itmp]['refid']=0;
				
				$total_dr_curr += (double)$vou_dtl[$itmp]['curr_dr'];
				$total_dr      += (double)$vou_dtl[$itmp]['dr'];
				$total_cr_curr += (double)$vou_dtl[$itmp]['curr_cr'];
				$total_cr      += (double)$vou_dtl[$itmp]['cr'];
				$itmp+=1;
			}
			else
			{
				$model_mas->rollback();
				$this->error("没有定义预收账款会计科目!");
			}
		}		
		//如果原币已平，但本位币不平，则记入损益
		if($total_dr != $total_cr)
		{
			$faccdef = D('Faccdefault')->relation(true)->where('code = \'EGOL\'')->find();
			//$fcurrmas = M('Currmas')->where('flag = \'Y\' and status_flg=\'Y\'')->find();
			if($faccdef)
			{
				$diff_amount = $total_dr - $total_cr; //差异金额
				
				$vou_dtl[$itmp]['masid']=$vouid;
				$vou_dtl[$itmp]['acc_code']=$faccdef['acc_code'];
				$vou_dtl[$itmp]['acc_title']=$faccdef['acc_title'];
				$vou_dtl[$itmp]['customer_id']=$ori_mas['acc_id'];
				$vou_dtl[$itmp]['supplier_id']=0;
				$vou_dtl[$itmp]['curr_code']=$ori_mas['curr_code'];
				$vou_dtl[$itmp]['curr_rate']=$ori_mas['curr_rate'];
				$vou_dtl[$itmp]['curr_dr']= 0;
				$vou_dtl[$itmp]['dr']=get_round($diff_amount < 0 ? $diff_amount*-1 : 0);
				$vou_dtl[$itmp]['curr_cr']= 0;
				$vou_dtl[$itmp]['cr']=get_round($diff_amount > 0 ? $diff_amount : 0);
				$vou_dtl[$itmp]['curr_open_amount']=0;
				$vou_dtl[$itmp]['open_amount']=0;
				$vou_dtl[$itmp]['refid']=0;
				
				$total_dr_curr += (double)$vou_dtl[$itmp]['curr_dr'];
				$total_dr      += (double)$vou_dtl[$itmp]['dr'];
				$total_cr_curr += (double)$vou_dtl[$itmp]['curr_cr'];
				$total_cr      += (double)$vou_dtl[$itmp]['cr'];
				$itmp+=1;
			}
			else
			{
				$model_mas->rollback();
				$this->error("没有定义财务损益会计科目，或没有设置本位币!");
			}
		}
        
        $total_dr_curr = sprintf("%.2f", $total_dr_curr);
        $total_cr_curr = sprintf("%.2f", $total_cr_curr);
        $total_dr = sprintf("%.2f", $total_dr);
        $total_cr = sprintf("%.2f", $total_cr);        
		if($total_dr_curr!=$total_cr_curr || $total_dr!=$total_cr)
		{
				$model_mas->rollback();
				$this->error("借贷不平衡!($total_dr_curr-->$total_cr_curr)  ($total_dr-->$total_cr)");
		}
		
		// 核销，回写原始记录的open amount
		$deduct_flg = true;
		if($deduct_dtl)
		{
			$deduct_flg = deduct_gl($deduct_dtl);
			if($deduct_flg['flg']===false)
			{
				$model_mas->rollback();
				$this->error($deduct_flg['msg']);
			}
		}
		
		//写入新分录
		$vou_item_flg = true;
		if($vou_dtl)
		{
			$vou_item_flg=$model_vou_item->addAll($vou_dtl);
		}
		
		
		if ($facheckmasid && $deduct_flg && $vouid && $vou_item_flg)
		{
			$model_mas->commit();
			$this->assign("jumpUrl",U('Finance/fa_checkin_edit?id='.$_REQUEST['id']));
			$this->success("操作已完成!");
		}
		else
		{
			$model_mas->rollback();
			$this->error("操作时发生错误!");
		}
		
    }
	//收付款及核销公用
	public function facheck_check_status($docid,$vou_status="'A'")
	{
		$model_mas = M("Facheckmas");
		$where = "id in (".$docid.") and status_flg in (".$vou_status.")";
		$chk = $model_mas->where($where)->find();
		if($chk)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	public function facheck_status_to_a()
	{
		if($this->facheck_check_status($_GET["id"],"'P'"))
		{
			$this->error('单据已过账');
			exit;
		}
		
		$model = M("Facheckmas");
		//$this->assign("jumpUrl",U('Finance/fa_checkin_list'));
		$data = array('status_flg'=>'A');
		$model->where("id in (".$_GET["id"].")")->setField($data);
		if ($model)
		{
			$this->success("启用成功!");
		}
		else
		{
			$this->error($model->getError());
		}
    }
	
	public function facheck_status_to_c()
	{
		if($this->facheck_check_status($_GET["id"],"'P'"))
		{
			$this->error('单据已过账');
			exit;
		}
		
		$model = M("Facheckmas");
		//$this->assign("jumpUrl",U('Finance/fa_checkin_list'));
		$data = array('status_flg'=>'C');
		$model->where("id in (".$_GET["id"].")")->setField($data);
		if ($model)
		{
			$this->success("取消成功!");			
		}
		else
		{
			$this->error($model->getError());
		}
    }
	
	
	//往来付款和核销
	public function fa_checkout_list()
	{
	
		$s_status_flg = $_REQUEST['s_status_flg'];
		$keywords = $_REQUEST['keywords'];
		import("ORG.Util.Page"); // 导入分页类
		
		$model=D("FacheckmasView");
		$strwhere="Facheckmas.mas_code = 'APCHKOUT'";
		if($s_status_flg){$strwhere.=" and Facheckmas.status_flg like '$s_status_flg'";}
		if($keywords){$strwhere.=" and (Facheckmas.mas_no like '%$keywords%' or Facheckmas.remark like '%$keywords%' or Supplier.title like '%$keywords%')";}	
		
		$count      = $model->where($strwhere)->count(); // 查询满足要求的总记录数
		$Page       = new Page($count,(int)C('LIST_PAGESIZE')==''?'10':C('LIST_PAGESIZE')); // 实例化分页类传入总记录数和每页显示的记录数 
		$Page->parameter   .=   "&s_status_flg=".urlencode($s_status_flg);   //传递查询条件
		$Page->parameter   .=   "&keywords=".urlencode($keywords);
		$show       = $Page->show(); // 分页显示输出
		
		$datalist = $model->where($strwhere) -> order("id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign("datalist",$datalist);
		$this->assign('page',$show); // 赋值分页输出
		
		$this->assign('s_status_flg',$s_status_flg);
		$this->assign('keywords',$keywords);
		
		//C('SHOW_PAGE_TRACE',true);
		$this->display();
    }
	public function fa_checkout_add()
	{		
		if($_POST['action_flg']=='CALLBACK')
		{
			$acc_info['acc_id']=$_POST['acc_id'];
			$acc_info['acc_title']=$_POST['acc_title'];
			$this->assign("acc_info",$acc_info);
			
			$currmas['code']=$_POST['curr_code'];
			$currmas['rate']=$_POST['curr_rate'];
			$this->assign("currmas",$currmas);
			
			$this->assign("fadate",$_POST['fadate']);
			
			$subQuery = D('Faccdefault')->relation(true)->field('acc_code')->where('code in (\'SINV-AP\',\'PREPAID\') and status_flg=\'Y\'')->select(false);
			$model = D('VouitemView');
			$mydata_item = $model->where('supplier_id='.$acc_info['acc_id'].' and curr_code=\''.$currmas['code'].'\' and (curr_open_amount!=0 or open_amount!=0) and acc_code in '.$subQuery)->order('id')->select();
			$this->assign("mydata_item",$mydata_item);
			
			$writeoff_item_num = count($mydata_item);
			$this->assign("writeoff_item_num",$writeoff_item_num);
		}
		else
		{
			$currmas = M('Currmas')->where("flag='Y' and status_flg='Y'")->find();
			$this->assign("currmas",$currmas);			
		
			$this->assign("fadate",date('Y-m-d'));
		}
		
		$faccdefault = D('Faccdefault')->relation(true)->where('code like \'BANK\' and status_flg=\'Y\'')->find();
		$this->assign("faccdefault",$faccdefault);
		
		$this->display();
    }
	
	public function fa_checkout_add_save()
	{		
		$model_mas = D("Facheckmas");
		$model_item = D("Facheckitem");
		$model_mas->startTrans();
		
		if ($model_mas->create())
		{			
			$model_mas->fadate=strtotime($_POST['fadate']);
			$model_mas->mas_no = facheck_masno_create($_POST['mas_code'],strtotime($_POST['fadate']));
			$model_mas->createtime=time();
			$model_mas->creater=$_SESSION[C('USER_AUTH_KEY')];
			$newid=$model_mas->add();
			
			$itmp = 0;
			foreach($_POST['checkitem'] as $item)
			{
				if($item['acc_code'] && $item['curr_dr'])
				{
					$data[$itmp]['masid']=$newid;
					$data[$itmp]['acc_code']=$item['acc_code'];
					$data[$itmp]['acc_title']=$item['acc_title'];
					$data[$itmp]['customer_id']=0;
					$data[$itmp]['supplier_id']=0;
					$data[$itmp]['curr_code']=$_POST['curr_code'];
					$data[$itmp]['curr_rate']=$_POST['curr_rate'];
					$data[$itmp]['curr_dr']=0;
					$data[$itmp]['dr']=0;
					$data[$itmp]['curr_cr']=get_round($item['curr_dr']);
					$data[$itmp]['cr']=get_round((double)$item['curr_dr']*(double)$_POST['curr_rate']);
					$data[$itmp]['curr_open_amount']=get_round($data[$itmp]['curr_cr']);
					$data[$itmp]['open_amount']=get_round($data[$itmp]['cr']);
					$data[$itmp]['refid']=0;
					$data[$itmp]['ref_remark']=$_POST['remark'];
					$itmp += 1;
				}
			}
			foreach($_POST['vouitem'] as $item)
			{
				if($item['writeoff']=='Y' && $item['acc_code'] && $item['curr_open_amount'])
				{
					$data[$itmp]['masid']=$newid;
					$data[$itmp]['acc_code']=$item['acc_code'];
					$data[$itmp]['acc_title']=$item['acc_title'];
					$data[$itmp]['customer_id']=0;
					$data[$itmp]['supplier_id']=$_POST['acc_id'];
					$data[$itmp]['curr_code']=$item['curr_code'];
					$data[$itmp]['curr_rate']=$item['curr_rate'];
					$data[$itmp]['curr_dr']=get_round($item['curr_dr']);
					$data[$itmp]['dr']=get_round($item['dr']);
					$data[$itmp]['curr_cr']=get_round($item['curr_cr']);
					$data[$itmp]['cr']=get_round($item['cr']);
					$data[$itmp]['curr_open_amount']=get_round($item['curr_open_amount']);
					$data[$itmp]['open_amount']=get_round((double)$item['curr_open_amount']*(double)$item['curr_rate']);
					$data[$itmp]['refid']=$item['detail_id'];
					$data[$itmp]['ref_remark']=$item['ref_remark'];
					$itmp += 1;
				}
			}
			
			$item_flg = true;
			if($data)
			{
				$item_flg = $model_item->addAll($data);
			}

			if($newid && $item_flg)
			{
				$model_mas->commit();
				$this->assign("jumpUrl",U('Finance/fa_checkout_edit?id='.$newid));
				$this->success("操作已完成!");
			}
			else
			{
				$model_mas->rollback();
				$this->error('操作时发生错误。');
			}
						
		}
		else
		{
			$model_mas->rollback();
			$this->error($model_mas->getError());
		}
    }
	
	public function fa_checkout_edit()
	{		
		$map = array();
        $map["where"]["id"] = $_GET["id"];

        $model= D("FacheckmasView");
        $mydata = $model->find($map);
		$this->assign("mydata",$mydata);
		
		$model_item= D("FacheckitemView");
        $mydata_item = $model_item->where("masid = ".$_GET["id"]." and refid=0")->select();
		$this->assign("mydata_item",$mydata_item);
		$item_num = count($mydata_item);
		$this->assign("item_num",$item_num);
		
		if($mydata['status_flg']=='A') //活动状态下，需要把可以核销的明细导出来，并与做单时的数据匹配
		{
			$subQuery = D('Faccdefault')->relation(true)->field('acc_code')->where('code in (\'SINV-AP\',\'PREPAID\') and status_flg=\'Y\'')->select(false);
			$model_vou = D('VouitemView');
			$writeoff_item = $model_vou->where('supplier_id='.$mydata['acc_id'].' and curr_code=\''.$mydata['curr_code'].'\' and (curr_open_amount!=0 or open_amount!=0) and acc_code in '.$subQuery)->order('id')->select();
			$writeoff_tmp1 = $model_item->where("masid = ".$_GET["id"]." and refid>0")->select();
			
			foreach($writeoff_tmp1 as $item)
			{
				$writeoff_tmp2[$item['refid']]['refid']=$item['refid'];
				$writeoff_tmp2[$item['refid']]['ref_remark']=$item['ref_remark'];
				$writeoff_tmp2[$item['refid']]['curr_writeoff_amount']=$item['curr_open_amount'];
				$writeoff_tmp2[$item['refid']]['writeoff_amount']=$item['open_amount'];
				$writeoff_tmp2[$item['refid']]['writeoff']='Y';
			}
			foreach($writeoff_item as $key=>$value)
			{
				if((double)$writeoff_tmp2[$value['id']]['refid'] > 0)
				{
					$writeoff_item[$key]['curr_writeoff_amount'] = (double)$writeoff_tmp2[$value['id']]['curr_writeoff_amount'] > (double)$value['curr_open_amount'] ? $value['curr_open_amount'] : $writeoff_tmp2[$value['id']]['curr_writeoff_amount'];
					$writeoff_item[$key]['writeoff_amount'] = (double)$writeoff_tmp2[$value['id']]['writeoff_amount'] > (double)$value['open_amount'] ? $value['open_amount'] : $writeoff_tmp2[$value['id']]['writeoff_amount'];
					$writeoff_item[$key]['writeoff'] = $writeoff_tmp2[$value['id']]['writeoff']=='Y' ? 'Y' : 'N';
					$writeoff_item[$key]['mas_remark'] = $writeoff_tmp2[$value['id']]['ref_remark']=='' ? $value['mas_remark'] : $writeoff_tmp2[$value['id']]['ref_remark'];
					$writeoff_item[$key]['refid'] = $writeoff_tmp2[$value['id']]['refid'];
				}
				else
				{
					$writeoff_item[$key]['curr_writeoff_amount'] = 0;
					$writeoff_item[$key]['writeoff_amount'] = 0;
					$writeoff_item[$key]['writeoff'] = 'N';
					$writeoff_item[$key]['mas_remark'] = $value['mas_remark'];
					$writeoff_item[$key]['refid'] = $value['id'];
				}
			}
			//var_dump($writeoff_item);
			$this->assign("writeoff_item",$writeoff_item);
			$writeoff_item_num = count($writeoff_item);
			$this->assign("writeoff_item_num",$writeoff_item_num);
		}
		else //不是活动状态，则直接读取做单时的数据
		{
			$writeoff_item = $model_item->where("masid = ".$_GET["id"]." and refid>0")->select();
			foreach($writeoff_item as $key=>$value)
			{
					$writeoff_item[$key]['curr_writeoff_amount'] = $value['curr_open_amount'];
					$writeoff_item[$key]['writeoff_amount'] = $value['open_amount'];
					$writeoff_item[$key]['writeoff'] = 'Y';
					$writeoff_item[$key]['mas_remark'] = $value['ref_remark'];
					
			}
			$this->assign("writeoff_item",$writeoff_item);
			$writeoff_item_num = count($writeoff_item);
			$this->assign("writeoff_item_num",$writeoff_item_num);
		}
		
		
		$currmas = M('Currmas')->where("flag='Y' and status_flg='Y'")->find();
		$this->assign("currmas",$currmas);
		
		$faccdefault = D('Faccdefault')->relation(true)->where('code like \'BANK\' and status_flg=\'Y\'')->find();
		$this->assign("faccdefault",$faccdefault);
		
		$this->display();
    }
	
	public function fa_checkout_edit_save()
	{		
		if(!$this->facheck_check_status($_REQUEST['id'],"'A','E'"))
		{
			$this->error('单据状态要求为【活动中】');
			exit;
		}
		
		$model_mas = D("Facheckmas");
		$model_item = D("Facheckitem");
		$model_mas->startTrans();
		
		if ($model_mas->create())
		{			
			$newid=$_POST['id'];
			$model_mas->fadate=strtotime($_POST['fadate']);			
			$model_mas->save();
			
			$delid = true;
			$itemcount = $model_item->where('masid='.$newid)->count();
			if($itemcount)$delid=$model_item->where('masid='.$newid)->delete();
			
			$itmp = 0;
			foreach($_POST['checkitem'] as $item)
			{
				if($item['acc_code'] && $item['curr_dr'])
				{
					$data[$itmp]['masid']=$newid;
					$data[$itmp]['acc_code']=$item['acc_code'];
					$data[$itmp]['acc_title']=$item['acc_title'];
					$data[$itmp]['customer_id']=0;
					$data[$itmp]['supplier_id']=0;
					$data[$itmp]['curr_code']=$_POST['curr_code'];
					$data[$itmp]['curr_rate']=$_POST['curr_rate'];
					$data[$itmp]['curr_dr']=0;
					$data[$itmp]['dr']=0;
					$data[$itmp]['curr_cr']=get_round($item['curr_dr']);
					$data[$itmp]['cr']=get_round((double)$item['curr_dr']*(double)$_POST['curr_rate']);
					$data[$itmp]['curr_open_amount']=get_round($data[$itmp]['curr_cr']);
					$data[$itmp]['open_amount']=get_round($data[$itmp]['cr']);
					$data[$itmp]['refid']=0;
					$data[$itmp]['ref_remark']=$_POST['remark'];
					$itmp += 1;
				}
			}
			foreach($_POST['vouitem'] as $item)
			{
				if($item['writeoff']=='Y' && $item['acc_code'] && $item['curr_open_amount'])
				{
					$data[$itmp]['masid']=$newid;
					$data[$itmp]['acc_code']=$item['acc_code'];
					$data[$itmp]['acc_title']=$item['acc_title'];
					$data[$itmp]['customer_id']=0;
					$data[$itmp]['supplier_id']=$_POST['acc_id'];
					$data[$itmp]['curr_code']=$item['curr_code'];
					$data[$itmp]['curr_rate']=$item['curr_rate'];
					$data[$itmp]['curr_dr']=get_round($item['curr_dr']);
					$data[$itmp]['dr']=get_round($item['dr']);
					$data[$itmp]['curr_cr']=get_round($item['curr_cr']);
					$data[$itmp]['cr']=get_round($item['cr']);
					$data[$itmp]['curr_open_amount']=get_round($item['curr_open_amount']);
					$data[$itmp]['open_amount']=get_round((double)$item['curr_open_amount']*(double)$item['curr_rate']);
					$data[$itmp]['refid']=$item['detail_id'];
					$data[$itmp]['ref_remark']=$item['ref_remark'];
					$itmp += 1;
				}
			}
			$item_flg = true;
			if($data)
			{
				$item_flg = $model_item->addAll($data);
			}
			if($newid && $delid && $item_flg)
			{
				$model_mas->commit();
				$this->assign("jumpUrl",U('Finance/fa_checkout_edit?id='.$newid));
				$this->success("操作已完成!");
			}
			else
			{
				$model_mas->rollback();
				$this->error('操作时发生错误。');
			}
						
		}
		else
		{
			$model_mas->rollback();
			$this->error($model_mas->getError());
		}
    }
	public function fa_checkout_save_post()
	{		
		if(!$this->facheck_check_status($_REQUEST['id']))
		{
			$this->error('单据状态要求为【活动中】');
			exit;
		}
		
		if(!fiscalyp_check_common($_REQUEST['fadate'],1))
		{
			$this->error('会计期间已关闭');
			exit;
		}
		
		$model_mas = D("Facheckmas");
		$model_item = D("Facheckitem");
		$model_mas->startTrans();
		
		if ($model_mas->create())
		{			
			$newid=$_POST['id'];
			$model_mas->fadate=strtotime($_POST['fadate']);
			$model_mas->posttime=time();
			$model_mas->poster=$_SESSION[C('USER_AUTH_KEY')];
			$model_mas->status_flg='P';
			
			$model_mas->save();
			
			$delid = true;
			$itemcount = $model_item->where('masid='.$newid)->count();
			if($itemcount)$delid=$model_item->where('masid='.$newid)->delete();
			
			//生成总账MAS
			$model_vou_mas = M('Voumas');
			$model_vou_item= M('Vouitem');
			
			$data_vou_mas['fadate']=strtotime($_POST['fadate']);
			$data_vou_mas['refcode']=$_POST['mas_code'];
			$data_vou_mas['refid']=$newid;
			$data_vou_mas['vouno']=vouno_create(strtotime($_POST['fadate']));
			$data_vou_mas['remark']='从'.$_POST['mas_code'].'#'.$_POST['mas_no'].'#'.$_POST['remark'];
			$data_vou_mas['createtime']=time();
			$data_vou_mas['creater']=$_SESSION[C('USER_AUTH_KEY')];
			$data_vou_mas['posttime']=time();
			$data_vou_mas['poster']=$_SESSION[C('USER_AUTH_KEY')];
			$data_vou_mas['status_flg']='P';
			$vouid=$model_vou_mas->data($data_vou_mas)->add();
			
			$itmp = 0;
			$total_dr_curr = 0;
			$total_dr = 0;
			$total_cr_curr = 0;
			$total_cr = 0;
			foreach($_POST['checkitem'] as $item)
			{
				if($item['acc_code'] && $item['curr_dr'])
				{
					$data[$itmp]['masid']=$newid;
					$data[$itmp]['acc_code']=$item['acc_code'];
					$data[$itmp]['acc_title']=$item['acc_title'];
					$data[$itmp]['customer_id']=0;
					$data[$itmp]['supplier_id']=0;
					$data[$itmp]['curr_code']=$_POST['curr_code'];
					$data[$itmp]['curr_rate']=$_POST['curr_rate'];
					$data[$itmp]['curr_dr']=0;
					$data[$itmp]['dr']=0;
					$data[$itmp]['curr_cr']=get_round($item['curr_dr']);
					$data[$itmp]['cr']=get_round((double)$item['curr_dr']*(double)$_POST['curr_rate']);
					$data[$itmp]['curr_open_amount']=get_round($data[$itmp]['curr_dr']);
					$data[$itmp]['open_amount']=get_round($data[$itmp]['dr']);
					$data[$itmp]['refid']=0;
					$data[$itmp]['ref_remark']=$_POST['remark'];
					
					//要生成新凭证的数据(正方向)(本次付款的数据)
					$vou_dtl[$itmp]['masid']=$vouid;
					$vou_dtl[$itmp]['acc_code']=$item['acc_code'];
					$vou_dtl[$itmp]['acc_title']=$item['acc_title'];
					$vou_dtl[$itmp]['customer_id']=0;
					$vou_dtl[$itmp]['supplier_id']=0;
					$vou_dtl[$itmp]['curr_code']=$_POST['curr_code'];
					$vou_dtl[$itmp]['curr_rate']=$_POST['curr_rate'];
					$vou_dtl[$itmp]['curr_dr']=0;
					$vou_dtl[$itmp]['dr']=0;
					$vou_dtl[$itmp]['curr_cr']=get_round($item['curr_dr']);
					$vou_dtl[$itmp]['cr']=get_round((double)$item['curr_dr']*(double)$_POST['curr_rate']);
					$vou_dtl[$itmp]['curr_open_amount']=0;
					$vou_dtl[$itmp]['open_amount']=0;
					$vou_dtl[$itmp]['refid']=0;
					$data[$itmp]['ref_remark']=$item['ref_remark'];
					
					$total_dr_curr += (double)$vou_dtl[$itmp]['curr_dr'];
					$total_dr      += (double)$vou_dtl[$itmp]['dr'];
					$total_cr_curr += (double)$vou_dtl[$itmp]['curr_cr'];
					$total_cr      += (double)$vou_dtl[$itmp]['cr'];
					
					$itmp += 1;
				}
			}
			foreach($_POST['vouitem'] as $item)
			{
				if($item['writeoff']=='Y' && $item['acc_code'] && $item['curr_open_amount'])
				{
					$data[$itmp]['masid']=$newid;
					$data[$itmp]['acc_code']=$item['acc_code'];
					$data[$itmp]['acc_title']=$item['acc_title'];
					$data[$itmp]['customer_id']=0;
					$data[$itmp]['supplier_id']=$_POST['acc_id'];
					$data[$itmp]['curr_code']=$item['curr_code'];
					$data[$itmp]['curr_rate']=$item['curr_rate'];
					$data[$itmp]['curr_dr']=get_round($item['curr_dr']);
					$data[$itmp]['dr']=get_round($item['dr']);
					$data[$itmp]['curr_cr']=get_round($item['curr_cr']);
					$data[$itmp]['cr']=get_round($item['cr']);
					$data[$itmp]['curr_open_amount']=get_round($item['curr_open_amount']);
					$data[$itmp]['open_amount']=get_round((double)$item['curr_open_amount']*(double)$item['curr_rate']);
					$data[$itmp]['refid']=$item['detail_id'];
					$data[$itmp]['ref_remark']=$item['ref_remark'];
					
					//要冲销并回写的数据
					$deduct_dtl[$itmp]['refid']=$item['detail_id'];
					$deduct_dtl[$itmp]['curr_open_amount']=$item['curr_open_amount'];
					$deduct_dtl[$itmp]['open_amount']=(double)$item['curr_open_amount']*(double)$item['curr_rate'];
				
					//要生成新凭证的数据(反方向)
					$vou_dtl[$itmp]['masid']=$vouid;
					$vou_dtl[$itmp]['acc_code']=$item['acc_code'];
					$vou_dtl[$itmp]['acc_title']=$item['acc_title'];
					$vou_dtl[$itmp]['customer_id']=0;
					$vou_dtl[$itmp]['supplier_id']=$_POST['acc_id'];
					$vou_dtl[$itmp]['curr_code']=$item['curr_code'];
					$vou_dtl[$itmp]['curr_rate']=$item['curr_rate'];
					$vou_dtl[$itmp]['curr_dr']=get_round((double)$item['curr_dr'] > 0 ? 0 : $item['curr_open_amount']);
					$vou_dtl[$itmp]['dr']=get_round((double)$item['dr'] > 0 ? 0 : (double)$item['curr_open_amount']*(double)$item['curr_rate']);
					$vou_dtl[$itmp]['curr_cr']=get_round((double)$item['curr_cr'] > 0 ? 0 : $item['curr_open_amount']);
					$vou_dtl[$itmp]['cr']=get_round((double)$item['cr'] > 0 ? 0 : (double)$item['curr_open_amount']*(double)$item['curr_rate']);
					$vou_dtl[$itmp]['curr_open_amount']=0;
					$vou_dtl[$itmp]['open_amount']=0;
					$vou_dtl[$itmp]['refid']=$item['detail_id'];
					
					$total_dr_curr += (double)$vou_dtl[$itmp]['curr_dr'];
					$total_dr      += (double)$vou_dtl[$itmp]['dr'];
					$total_cr_curr += (double)$vou_dtl[$itmp]['curr_cr'];
					$total_cr      += (double)$vou_dtl[$itmp]['cr'];
					
					$itmp += 1;
				}
			}
		
		//如果付款没有核销完，则记入预付款
		if($total_dr_curr != $total_cr_curr)
		{
			$faccdef = D('Faccdefault')->relation(true)->where('code = \'PREPAID\'')->find();
			if($faccdef)
			{
				$diff_amount = $total_dr_curr - $total_cr_curr; //差异金额
				
				$vou_dtl[$itmp]['masid']=$vouid;
				$vou_dtl[$itmp]['acc_code']=$faccdef['acc_code'];
				$vou_dtl[$itmp]['acc_title']=$faccdef['acc_title'];
				$vou_dtl[$itmp]['customer_id']=0;
				$vou_dtl[$itmp]['supplier_id']=$_POST['acc_id'];
				$vou_dtl[$itmp]['curr_code']=$_POST['curr_code'];
				$vou_dtl[$itmp]['curr_rate']=$_POST['curr_rate'];
				$vou_dtl[$itmp]['curr_dr']= get_round($diff_amount < 0 ? $diff_amount*-1 : 0);
				$vou_dtl[$itmp]['dr']=get_round($diff_amount < 0 ? $diff_amount*-1*(float)$_POST['curr_rate'] : 0);
				$vou_dtl[$itmp]['curr_cr']= get_round($diff_amount > 0 ? $diff_amount : 0);
				$vou_dtl[$itmp]['cr']=get_round($diff_amount > 0 ? $diff_amount*(float)$_POST['curr_rate'] : 0);
				$vou_dtl[$itmp]['curr_open_amount']=get_round($diff_amount > 0 ? $vou_dtl[$itmp]['curr_cr'] : $vou_dtl[$itmp]['curr_dr']);
				$vou_dtl[$itmp]['open_amount']=get_round($diff_amount > 0 ? $vou_dtl[$itmp]['cr'] : $vou_dtl[$itmp]['dr']);
				$vou_dtl[$itmp]['refid']=0;
				
				$total_dr_curr += (double)$vou_dtl[$itmp]['curr_dr'];
				$total_dr      += (double)$vou_dtl[$itmp]['dr'];
				$total_cr_curr += (double)$vou_dtl[$itmp]['curr_cr'];
				$total_cr      += (double)$vou_dtl[$itmp]['cr'];
				$itmp+=1;
			}
			else
			{
				$model_mas->rollback();
				$this->error("没有定义预付账款会计科目!");
			}
		}		
		//如果原币已平，但本位币不平，则记入损益
		if($total_dr != $total_cr)
		{
			$faccdef = D('Faccdefault')->relation(true)->where('code = \'EGOL\'')->find();
			//$fcurrmas = M('Currmas')->where('flag = \'Y\' and status_flg=\'Y\'')->find();
			if($faccdef)
			{
				$diff_amount = $total_dr - $total_cr; //差异金额
				
				$vou_dtl[$itmp]['masid']=$vouid;
				$vou_dtl[$itmp]['acc_code']=$faccdef['acc_code'];
				$vou_dtl[$itmp]['acc_title']=$faccdef['acc_title'];
				$vou_dtl[$itmp]['customer_id']=0;
				$vou_dtl[$itmp]['supplier_id']=$_POST['acc_id'];
				$vou_dtl[$itmp]['curr_code']=$_POST['curr_code'];
				$vou_dtl[$itmp]['curr_rate']=$_POST['curr_rate'];
				$vou_dtl[$itmp]['curr_dr']= 0;
				$vou_dtl[$itmp]['dr']=get_round($diff_amount < 0 ? $diff_amount*-1 : 0);
				$vou_dtl[$itmp]['curr_cr']= 0;
				$vou_dtl[$itmp]['cr']=get_round($diff_amount > 0 ? $diff_amount : 0);
				$vou_dtl[$itmp]['curr_open_amount']=0;
				$vou_dtl[$itmp]['open_amount']=0;
				$vou_dtl[$itmp]['refid']=0;
				
				$total_dr_curr += (double)$vou_dtl[$itmp]['curr_dr'];
				$total_dr      += (double)$vou_dtl[$itmp]['dr'];
				$total_cr_curr += (double)$vou_dtl[$itmp]['curr_cr'];
				$total_cr      += (double)$vou_dtl[$itmp]['cr'];
				$itmp+=1;
			}
			else
			{
				$model_mas->rollback();
				$this->error("没有定义财务损益会计科目，或没有设置本位币!");
			}
		}
        $total_dr_curr = sprintf("%.2f", $total_dr_curr);
        $total_cr_curr = sprintf("%.2f", $total_cr_curr);
        $total_dr = sprintf("%.2f", $total_dr);
        $total_cr = sprintf("%.2f", $total_cr);
		if($total_dr_curr!=$total_cr_curr || $total_dr!=$total_cr)
		{
				$model_mas->rollback();
				$this->error("借贷不平衡!");
		}
		
		
			$item_flg = true;
			if($data)
			{
				$item_flg = $model_item->addAll($data);
			}
			
			//生成总账ITEM
			// 核销，回写原始记录的open amount
			$deduct_flg = true;
			if($deduct_dtl)
			{
				$deduct_flg = deduct_gl($deduct_dtl);
				if($deduct_flg['flg']===false)
				{
					$model_mas->rollback();
					$this->error($deduct_flg['msg']);
				}
			}
		
			//写入新分录
			$vou_item_flg = true;
			if($vou_dtl)
			{
				$vou_item_flg=$model_vou_item->addAll($vou_dtl);
			}
			
			
			if($newid && $delid && $item_flg && $vouid && $vou_item_flg)
			{
				$model_mas->commit();
				$this->assign("jumpUrl",U('Finance/fa_checkout_edit?id='.$newid));
				$this->success("操作已完成!");
			}
			else
			{
				$model_mas->rollback();
				$this->error('操作时发生错误。');
			}
						
		}
		else
		{
			$model_mas->rollback();
			$this->error($model_mas->getError());
		}
	}
	
	public function fa_checkout_post()
	{		
		if(!$this->facheck_check_status($_REQUEST['id']))
		{
			$this->error('单据状态要求为【活动中】');
			exit;
		}
		
		$model_mas = D("Facheckmas");
		$model_item = D("Facheckitem");
		$model_mas->startTrans();
		
		$ori_id = $_REQUEST['id'];
		$ori_mas = $model_mas->find($ori_id);
		$ori_item = $model_item->where('masid='.$ori_id)->select();
		
		if(!fiscalyp_check_common($ori_mas['fadate'],1))
		{
			$this->error('会计期间已关闭');
			exit;
		}
		
		$data['id']=$_REQUEST['id'];
		$data['status_flg']='P';
		$data['posttime']=time();
		$data['poster']=$_SESSION[C('USER_AUTH_KEY')];
		
		$facheckmasid=$model_mas->save($data);

			
		//生成总账
			$model_vou_mas = M('Voumas');
			$model_vou_item= M('Vouitem');
			
			$data_vou_mas['fadate']=$ori_mas['fadate'];
			$data_vou_mas['refcode']=$ori_mas['mas_code'];
			$data_vou_mas['refid']=$ori_id;
			$data_vou_mas['vouno']=vouno_create($ori_mas['fadate']);
			$data_vou_mas['remark']='从'.$ori_mas['mas_code'].'#'.$ori_mas['mas_no'].'#'.$ori_mas['remark'];
			$data_vou_mas['createtime']=time();
			$data_vou_mas['creater']=$_SESSION[C('USER_AUTH_KEY')];
			$data_vou_mas['posttime']=time();
			$data_vou_mas['poster']=$_SESSION[C('USER_AUTH_KEY')];
			$data_vou_mas['status_flg']='P';
			$vouid=$model_vou_mas->data($data_vou_mas)->add();
			
		$itmp = 0;
		$total_dr_curr = 0;
		$total_dr = 0;
		$total_cr_curr = 0;
		$total_cr = 0;
		foreach($ori_item as $item)
		{
			if($item['refid'])
			{
				//要冲销并回写的数据
				$deduct_dtl[$itmp]['refid']=$item['refid'];
				$deduct_dtl[$itmp]['curr_open_amount']=$item['curr_open_amount'];
				$deduct_dtl[$itmp]['open_amount']=$item['open_amount'];
				
				//要生成新凭证的数据(反方向)
				$vou_dtl[$itmp]['masid']=$vouid;
				$vou_dtl[$itmp]['acc_code']=$item['acc_code'];
				$vou_dtl[$itmp]['acc_title']=$item['acc_title'];
				$vou_dtl[$itmp]['customer_id']=$item['customer_id'];
				$vou_dtl[$itmp]['supplier_id']=$item['supplier_id'];
				$vou_dtl[$itmp]['curr_code']=$item['curr_code'];
				$vou_dtl[$itmp]['curr_rate']=$item['curr_rate'];
				$vou_dtl[$itmp]['curr_dr']=get_round((double)$item['curr_dr'] > 0 ? 0 : $item['curr_open_amount']);
				$vou_dtl[$itmp]['dr']=get_round((double)$item['dr'] > 0 ? 0 : $item['open_amount']);
				$vou_dtl[$itmp]['curr_cr']=get_round((double)$item['curr_cr'] > 0 ? 0 : $item['curr_open_amount']);
				$vou_dtl[$itmp]['cr']=get_round((double)$item['cr'] > 0 ? 0 : $item['open_amount']);
				$vou_dtl[$itmp]['curr_open_amount']=0;
				$vou_dtl[$itmp]['open_amount']=0;
				$vou_dtl[$itmp]['refid']=$item['refid'];
				
			}
			else
			{
				//要生成新凭证的数据(正方向)(本次付款的数据)
				$vou_dtl[$itmp]['masid']=$vouid;
				$vou_dtl[$itmp]['acc_code']=$item['acc_code'];
				$vou_dtl[$itmp]['acc_title']=$item['acc_title'];
				$vou_dtl[$itmp]['customer_id']=$item['customer_id'];
				$vou_dtl[$itmp]['supplier_id']=$item['supplier_id'];
				$vou_dtl[$itmp]['curr_code']=$item['curr_code'];
				$vou_dtl[$itmp]['curr_rate']=$item['curr_rate'];
				$vou_dtl[$itmp]['curr_dr']=get_round($item['curr_dr']);
				$vou_dtl[$itmp]['dr']=get_round($item['dr']);
				$vou_dtl[$itmp]['curr_cr']=get_round($item['curr_cr']);
				$vou_dtl[$itmp]['cr']=get_round($item['cr']);
				$vou_dtl[$itmp]['curr_open_amount']=0;
				$vou_dtl[$itmp]['open_amount']=0;
				$vou_dtl[$itmp]['refid']=0;
			}
			$total_dr_curr += (double)$vou_dtl[$itmp]['curr_dr'];
			$total_dr      += (double)$vou_dtl[$itmp]['dr'];
			$total_cr_curr += (double)$vou_dtl[$itmp]['curr_cr'];
			$total_cr      += (double)$vou_dtl[$itmp]['cr'];
			$itmp+=1;
		}
		//如果付款没有核销完，则记入预付款
		if($total_dr_curr != $total_cr_curr)
		{
			$faccdef = D('Faccdefault')->relation(true)->where('code = \'PREPAID\'')->find();
			if($faccdef)
			{
				$diff_amount = $total_dr_curr - $total_cr_curr; //差异金额
				
				$vou_dtl[$itmp]['masid']=$vouid;
				$vou_dtl[$itmp]['acc_code']=$faccdef['acc_code'];
				$vou_dtl[$itmp]['acc_title']=$faccdef['acc_title'];
				$vou_dtl[$itmp]['customer_id']=0;
				$vou_dtl[$itmp]['supplier_id']=$ori_mas['acc_id'];
				$vou_dtl[$itmp]['curr_code']=$ori_mas['curr_code'];
				$vou_dtl[$itmp]['curr_rate']=$ori_mas['curr_rate'];
				$vou_dtl[$itmp]['curr_dr']= get_round($diff_amount < 0 ? $diff_amount*-1 : 0);
				$vou_dtl[$itmp]['dr']=get_round($diff_amount < 0 ? $diff_amount*-1*(float)$ori_mas['curr_rate'] : 0);
				$vou_dtl[$itmp]['curr_cr']= get_round($diff_amount > 0 ? $diff_amount : 0);
				$vou_dtl[$itmp]['cr']=get_round($diff_amount > 0 ? $diff_amount*(float)$ori_mas['curr_rate'] : 0);
				$vou_dtl[$itmp]['curr_open_amount']=get_round($diff_amount > 0 ? $vou_dtl[$itmp]['curr_cr'] : $vou_dtl[$itmp]['curr_dr']);
				$vou_dtl[$itmp]['open_amount']=get_round($diff_amount > 0 ? $vou_dtl[$itmp]['cr'] : $vou_dtl[$itmp]['dr']);
				$vou_dtl[$itmp]['refid']=0;
				
				$total_dr_curr += (double)$vou_dtl[$itmp]['curr_dr'];
				$total_dr      += (double)$vou_dtl[$itmp]['dr'];
				$total_cr_curr += (double)$vou_dtl[$itmp]['curr_cr'];
				$total_cr      += (double)$vou_dtl[$itmp]['cr'];
				$itmp+=1;
			}
			else
			{
				$model_mas->rollback();
				$this->error("没有定义预收账款会计科目!");
			}
		}		
		//如果原币已平，但本位币不平，则记入损益
		if($total_dr != $total_cr)
		{
			$faccdef = D('Faccdefault')->relation(true)->where('code = \'EGOL\'')->find();
			//$fcurrmas = M('Currmas')->where('flag = \'Y\' and status_flg=\'Y\'')->find();
			if($faccdef)
			{
				$diff_amount = $total_dr - $total_cr; //差异金额
				
				$vou_dtl[$itmp]['masid']=$vouid;
				$vou_dtl[$itmp]['acc_code']=$faccdef['acc_code'];
				$vou_dtl[$itmp]['acc_title']=$faccdef['acc_title'];
				$vou_dtl[$itmp]['customer_id']=0;
				$vou_dtl[$itmp]['supplier_id']=$ori_mas['acc_id'];
				$vou_dtl[$itmp]['curr_code']=$ori_mas['curr_code'];
				$vou_dtl[$itmp]['curr_rate']=$ori_mas['curr_rate'];
				$vou_dtl[$itmp]['curr_dr']= 0;
				$vou_dtl[$itmp]['dr']=get_round($diff_amount < 0 ? $diff_amount*-1 : 0);
				$vou_dtl[$itmp]['curr_cr']= 0;
				$vou_dtl[$itmp]['cr']=get_round($diff_amount > 0 ? $diff_amount : 0);
				$vou_dtl[$itmp]['curr_open_amount']=0;
				$vou_dtl[$itmp]['open_amount']=0;
				$vou_dtl[$itmp]['refid']=0;
				
				$total_dr_curr += (double)$vou_dtl[$itmp]['curr_dr'];
				$total_dr      += (double)$vou_dtl[$itmp]['dr'];
				$total_cr_curr += (double)$vou_dtl[$itmp]['curr_cr'];
				$total_cr      += (double)$vou_dtl[$itmp]['cr'];
				$itmp+=1;
			}
			else
			{
				$model_mas->rollback();
				$this->error("没有定义财务损益会计科目，或没有设置本位币!");
			}
		}
        $total_dr_curr = sprintf("%.2f", $total_dr_curr);
        $total_cr_curr = sprintf("%.2f", $total_cr_curr);
        $total_dr = sprintf("%.2f", $total_dr);
        $total_cr = sprintf("%.2f", $total_cr);
		if($total_dr_curr!=$total_cr_curr || $total_dr!=$total_cr)
		{
				$model_mas->rollback();
				$this->error("借贷不平衡!");
		}
		
		// 核销，回写原始记录的open amount
		$deduct_flg = true;
		if($deduct_dtl)
		{
			$deduct_flg = deduct_gl($deduct_dtl);
			if($deduct_flg['flg']===false)
			{
				$model_mas->rollback();
				$this->error($deduct_flg['msg']);
			}
		}
		
		//写入新分录
		$vou_item_flg = true;
		if($vou_dtl)
		{
			$vou_item_flg=$model_vou_item->addAll($vou_dtl);
		}
		
		
		if ($facheckmasid && $deduct_flg && $vouid && $vou_item_flg)
		{
			$model_mas->commit();
			$this->assign("jumpUrl",U('Finance/fa_checkout_edit?id='.$_REQUEST['id']));
			$this->success("操作已完成!");
		}
		else
		{
			$model_mas->rollback();
			$this->error("操作时发生错误!");
		}
		
    }
	//应付账款列表
	public function ap_list()
	{
		$model=D("VoudetailView");

		$keywords = $_REQUEST['keywords'];
		$this->assign('keywords',$keywords);
		
		import("ORG.Util.Page"); // 导入分页类

		$accdefault =  D('Faccdefault')->relation(true)->where('code in (\'SINV-AP\',\'PREPAID\')') -> select();
		$itmp = 0;
		foreach($accdefault as $row)
		{
			$acc_array[$itmp]=$row['acc_code'];
			$itmp += 1;
		}
		//echo implode(',',$acc_array);var_dump($acc_array);exit;		
		
		$strfield="supplier_title,curr_code,sum(curr_cr-curr_dr) as curr_open_amount,sum(cr-dr) as open_amount";
		$strgroup="supplier_title,curr_code";
		$strwhere="Vouitem.acc_code in(".implode(',',$acc_array).") and Vouitem.supplier_id>0";
		if($keywords){$strwhere.=" and Supplier.title like '%$keywords%'";}
		
		$subQuery = $model->field($strfield)->where($strwhere)->group($strgroup)->select(false);
		$count      = $model->table($subQuery.' a')->count(); // 查询满足要求的总记录数
		
		$Page       = new Page($count,(int)C('LIST_PAGESIZE')==''?'10':C('LIST_PAGESIZE')); // 实例化分页类传入总记录数和每页显示的记录数 
		$Page->parameter   .=   "&keywords=".urlencode($keywords);
		$show       = $Page->show(); // 分页显示输出
		
		$datalist = $model->field($strfield)
					->where($strwhere) -> limit($Page->firstRow.','.$Page->listRows)
					->group($strgroup) -> select();
		$this->assign("datalist",$datalist);
		$this->assign('page',$show); // 赋值分页输出
		

		$this->display();
    }
	//应收账款列表
	public function ar_list()
	{
		$model=D("VoudetailView");

		$keywords = $_REQUEST['keywords'];
		$this->assign('keywords',$keywords);
		
		import("ORG.Util.Page"); // 导入分页类

		$accdefault =  D('Faccdefault')->relation(true)->where('code in (\'INV-AR\',\'PRECOLLECTED\')') -> select();
		$itmp = 0;
		foreach($accdefault as $row)
		{
			$acc_array[$itmp]=$row['acc_code'];
			$itmp += 1;
		}
		//echo implode(',',$acc_array);var_dump($acc_array);exit;		
		
		$strfield="customer_title,curr_code,sum(curr_dr-curr_cr) as curr_open_amount,sum(dr-cr) as open_amount";
		$strgroup="customer_title,curr_code";
		$strwhere="Vouitem.acc_code in(".implode(',',$acc_array).") and Vouitem.customer_id>0";
		if($keywords){$strwhere.=" and Customer.title like '%$keywords%'";}
		
		$subQuery = $model->field($strfield)->where($strwhere)->group($strgroup)->select(false);
		$count      = $model->table($subQuery.' a')->count(); // 查询满足要求的总记录数
		
		$Page       = new Page($count,(int)C('LIST_PAGESIZE')==''?'10':C('LIST_PAGESIZE')); // 实例化分页类传入总记录数和每页显示的记录数 
		$Page->parameter   .=   "&keywords=".urlencode($keywords);
		$show       = $Page->show(); // 分页显示输出
		
		$datalist = $model->field($strfield)
					->where($strwhere) -> limit($Page->firstRow.','.$Page->listRows)
					->group($strgroup) -> select();
		$this->assign("datalist",$datalist);
		$this->assign('page',$show); // 赋值分页输出
		

		$this->display();
    }
	
	//试算平衡
	public function trial_balance()
	{		
		$yyyy = (int)$_REQUEST['f_year'];
		$mm = (int)$_REQUEST['f_period'];
		if(!$yyyy) $yyyy=date('Y');
		if(!$mm) $mm=date('m');
		$yyyymm = (int)$yyyy * 100 + (int)$mm;
		
		$this->assign("f_year",$yyyy);
		$this->assign("f_period",$mm);
		
		$model_mas = M('Voumas');
		$model_item = M('Vouitem');
		//期初
		$subQuery10 = $model_mas->field('id')->where("status_flg='P' and PERIOD_DIFF(FROM_UNIXTIME(fadate, '%Y%m'), ".$yyyymm.") < 0")->select(false);
		$subQuery11 = $model_item->field('acc_code,acc_title,sum(dr) as opening_dr,sum(cr) as opening_cr')->where("masid in ".$subQuery10)->group('acc_code,acc_title')->select(false);
		
		//本期
		$subQuery20 = $model_mas->field('id')->where("status_flg='P' and PERIOD_DIFF(FROM_UNIXTIME(fadate, '%Y%m'), ".$yyyymm.") = 0")->select(false);
		$subQuery21 = $model_item->field('acc_code,acc_title,sum(dr) as dr,sum(cr) as cr')->where("masid in ".$subQuery20)->group('acc_code,acc_title')->select(false);
		
		//FULL
		$subQuery3 = M()->table($subQuery11.' as a1')
					->field('IFNULL(a1.acc_code,b1.acc_code) as acc_code,IFNULL(a1.acc_title,b1.acc_title) as acc_title,IFNULL(a1.opening_dr,0)-IFNULL(a1.opening_cr,0) as opening,b1.dr,b1.cr,IFNULL(a1.opening_dr,0)-IFNULL(a1.opening_cr,0)+IFNULL(b1.dr,0)-IFNULL(b1.cr,0) as closing')
					->join('LEFT JOIN '.$subQuery21.' as b1 ON a1.acc_code=b1.acc_code')
					->union('SELECT IFNULL(a2.acc_code,b2.acc_code) as acc_code,IFNULL(a2.acc_title,b2.acc_title) as acc_title,IFNULL(a2.opening_dr,0)-IFNULL(a2.opening_cr,0) as opening,b2.dr,b2.cr,IFNULL(a2.opening_dr,0)-IFNULL(a2.opening_cr,0)+IFNULL(b2.dr,0)-IFNULL(b2.cr,0) as closing FROM '.$subQuery11.' as a2 RIGHT JOIN '.$subQuery21.' as b2 on a2.acc_code=b2.acc_code')
					->select(false);

		$datalist = M()->table($subQuery3.' as a')->order('acc_code asc')->select(); //重新排序
		//var_dump($datalist);var_dump($yyyymm);exit;
		$this->assign("datalist",$datalist);

		$this->display();
	}
	//科目明细表
	public function vou_detail()
	{
	
		$acc_code = $_REQUEST['acc_code'];
		$acc_title = $_REQUEST['acc_title'];
		$mas_fadate1 = $_REQUEST['mas_fadate1'];
		$mas_fadate2 = $_REQUEST['mas_fadate2'];
		$customer_title = $_REQUEST['customer_title'];
		$supplier_title = $_REQUEST['supplier_title'];
		$mas_remark = $_REQUEST['mas_remark'];
		
		if(!$mas_fadate1) $mas_fadate1 = date('Y-m').'-01';
		if(!$mas_fadate2) $mas_fadate2 = date('Y-m-d');
		
		$this->assign('acc_code',$acc_code);
		$this->assign('acc_title',$acc_title);		
		$this->assign('mas_fadate1',$mas_fadate1);
		$this->assign('mas_fadate2',$mas_fadate2);
		$this->assign('customer_title',$customer_title);
		$this->assign('supplier_title',$supplier_title);
		$this->assign('mas_remark',$mas_remark);
		

		import("ORG.Util.Page"); // 导入分页类
		
		$model=D("VouitemView");
		$strwhere="Voumas.status_flg='P'";
		if($acc_code){$strwhere.=" and Vouitem.acc_code = '$acc_code'";}
		if($acc_title){$strwhere.=" and Vouitem.acc_title like '%$acc_title%'";}
		if($mas_fadate1){$strwhere.=" and PERIOD_DIFF(FROM_UNIXTIME(Voumas.fadate, '%Y%m%d'),'".date('Ymd',strtotime($mas_fadate1))."') >= 0";}
		if($mas_fadate2){$strwhere.=" and PERIOD_DIFF(FROM_UNIXTIME(Voumas.fadate, '%Y%m%d'),'".date('Ymd',strtotime($mas_fadate2))."') <= 0";}
		if($customer_title){$strwhere.=" and Customer.title like '%$customer_title%'";}
		if($supplier_title){$strwhere.=" and Supplier.title like '%$supplier_title%'";}
		if($mas_remark){$strwhere.=" and Voumas.remark like '%$mas_remark%'";}
		
		
		$count      = $model->where($strwhere)->count(); // 查询满足要求的总记录数
		$Page       = new Page($count,(int)C('LIST_PAGESIZE')==''?'10':C('LIST_PAGESIZE')); // 实例化分页类传入总记录数和每页显示的记录数 
		$Page->parameter   .=   "&acc_code=".urlencode($acc_code);   //传递查询条件
		$Page->parameter   .=   "&acc_title=".urlencode($acc_title);
		$Page->parameter   .=   "&mas_fadate1=".urlencode($mas_fadate1);
		$Page->parameter   .=   "&mas_fadate2=".urlencode($mas_fadate2);
		$Page->parameter   .=   "&customer_title=".urlencode($customer_title);
		$Page->parameter   .=   "&supplier_title=".urlencode($supplier_title);
		$Page->parameter   .=   "&mas_remark=".urlencode($mas_remark);
		
		$show       = $Page->show(); // 分页显示输出
		
		$datalist = $model->where($strwhere) -> order("Voumas.fadate desc,Voumas.id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
		$this->assign("datalist",$datalist);
		$this->assign('page',$show); // 赋值分页输出
		
		$acc_total = $model->field('sum(curr_dr) as curr_dr,sum(dr) as dr,sum(curr_cr) as curr_cr,sum(cr) as cr')->where($strwhere) -> find();
		$this->assign("acc_total",$acc_total);
		
		//C('SHOW_PAGE_TRACE',true);
		$this->display();
    }
	//客户对账单（应收）
	public function ar_statement()
	{		
		$yyyy = (int)$_REQUEST['f_year'];
		$mm = (int)$_REQUEST['f_period'];
		$acc_id = $_REQUEST['acc_id'];
		$acc_title = $_REQUEST['acc_title'];
		if(!$yyyy) $yyyy=date('Y');
		if(!$mm) $mm=date('m');
		$yyyymm = (int)$yyyy * 100 + (int)$mm;
		
		$this->assign("f_year",$yyyy);
		$this->assign("f_period",$mm);
		$this->assign("acc_id",$acc_id);
		$this->assign("acc_title",$acc_title);
		
		if($yyyymm > 200001 && $acc_id)
		{
		
		$model_mas = M('Voumas');
		$model_item = D('VouitemView');
		
		$model_sp_mas = M('Spmas');
		$model_sp_dteail = D('SpdetailView');
		
		$model_check = D('FacheckitemView');
		
		$model_faccdefault = D('Faccdefault');
		
		$faccdefault = $model_faccdefault->relation(true)->where('status_flg=\'Y\' and code in (\'INV-AR\',\'PRECOLLECTED\')')->select();
		foreach($faccdefault as $row)
		{
			$faccdef[$row['acc_code']]=$row['acc_code'];
		}
		
		//期初
		$subQuery10 = $model_mas->field('id')->where("status_flg='P' and PERIOD_DIFF(FROM_UNIXTIME(fadate, '%Y%m'), ".$yyyymm.") < 0")->select(false);
		$datalist_opening = $model_item->field('acc_code,acc_title,sum(dr-cr) as opening')
							->where("acc_code in (".implode(',',$faccdef).") and customer_id=$acc_id  and masid in ".$subQuery10)
							->group('acc_code,acc_title')->select();
		$this->assign("datalist_opening",$datalist_opening);
		
		//本期销售、退货明细
		$subQuery21 = $model_sp_dteail->field("mas_fadate,mas_code,curr_rate,stk_code,stk_title,spec,stk_uom,qty,price,tax_rate,disc_rate,case when mas_code='RNC' then amount1*-1*curr_rate else amount1*curr_rate end as amount1,case when mas_code='RNC' then amount2*-1*curr_rate else amount2*curr_rate end as amount2,0 as amount3")
							->where("Spmas.acc_id=$acc_id and Spmas.mas_code in('SO','RNC') and PERIOD_DIFF(FROM_UNIXTIME(Spmas.fadate, '%Y%m'), ".$yyyymm.") = 0")
							->select(false);
		//收款明细（开单时直接收、退款）
		$subQuery22 = $model_sp_mas->field("fadate as mas_fadate,concat(mas_code,'-','CHECK') as mas_code,curr_rate,'' as stk_code,case when mas_code='RNC' then '在退货单上退款' else '在销售单上收款' end as stk_title,'' as spec,'' as stk_uom,0 as qty,0 as price,0 as tax_rate,0 as disc_rate,0 as amount1,0 as amount2,case when mas_code='RNC' then check_amount*-1*curr_rate else check_amount*curr_rate end as amount3")
							->where("acc_id=$acc_id and mas_code in('SO','RNC') and PERIOD_DIFF(FROM_UNIXTIME(fadate, '%Y%m'), ".$yyyymm.") = 0 and status_flg='P' and check_amount>0")
							->select(false);
		//收款明细（单独的收款）
		$subQuery23 = $model_check->field("mas_fadate,'ARCHKIN' as mas_code,curr_rate,'' as stk_code,'收款' as stk_title,'' as spec,'' as stk_uom,0 as qty,0 as price,0 as tax_rate,0 as disc_rate,0 as amount1,0 as amount2,dr as amount3")
							->where("Facheckmas.acc_id=$acc_id and Facheckmas.mas_code in('ARCHKIN') and PERIOD_DIFF(FROM_UNIXTIME(Facheckmas.fadate, '%Y%m'), ".$yyyymm.") = 0 and Facheckmas.status_flg='P' and Facheckitem.refid=0")
							->select(false);
		//调账收、退款
		$subQuery24 = $model_item->field("mas_fadate,'VOUMAS' as mas_code,curr_rate,'' as stk_code,'调整' as stk_title,'' as spec,'' as stk_uom,0 as qty,0 as price,0 as tax_rate,0 as disc_rate,0 as amount1,0 as amount2,case when dr>0 then dr else cr*-1 end as amount3")
							->where("Vouitem.acc_code in (".implode(',',$faccdef).") and Vouitem.customer_id=$acc_id and Voumas.refcode in('VOUMAS','') and PERIOD_DIFF(FROM_UNIXTIME(Voumas.fadate, '%Y%m'), ".$yyyymm.") = 0 and Voumas.status_flg='P' and Vouitem.refid=0")
							->select(false);
		//汇兑损益
		$subQuery25 = $model_item->field("mas_fadate,'VOUMAS' as mas_code,curr_rate,'' as stk_code,'汇兑损益' as stk_title,'' as spec,'' as stk_uom,0 as qty,0 as price,0 as tax_rate,0 as disc_rate,0 as amount1,0 as amount2,case when dr>0 then dr else cr*-1 end as amount3")
							->where("curr_dr=0 and curr_cr=0 and dr-cr!=0 and Vouitem.customer_id=$acc_id and PERIOD_DIFF(FROM_UNIXTIME(Voumas.fadate, '%Y%m'), ".$yyyymm.") = 0 and Voumas.status_flg='P' and Vouitem.refid=0")
							->select(false);
		//FULL
		$subQuery3 = M()->table($subQuery21.' as a1')
					->field('mas_fadate,mas_code,curr_rate,stk_code,stk_title,spec,stk_uom,qty,price,tax_rate,disc_rate,amount1,amount2,amount3')
					->union('SELECT mas_fadate,mas_code,curr_rate,stk_code,stk_title,spec,stk_uom,qty,price,tax_rate,disc_rate,amount1,amount2,amount3 FROM '.$subQuery22.' as a2',true)
					->union('SELECT mas_fadate,mas_code,curr_rate,stk_code,stk_title,spec,stk_uom,qty,price,tax_rate,disc_rate,amount1,amount2,amount3 FROM '.$subQuery23.' as a3',true)
					->union('SELECT mas_fadate,mas_code,curr_rate,stk_code,stk_title,spec,stk_uom,qty,price,tax_rate,disc_rate,amount1,amount2,amount3 FROM '.$subQuery24.' as a4',true)
					->union('SELECT mas_fadate,mas_code,curr_rate,stk_code,stk_title,spec,stk_uom,qty,price,tax_rate,disc_rate,amount1,amount2,amount3 FROM '.$subQuery25.' as a5',true)
					->select(false);

		$datalist = M()->table($subQuery3.' as a')->order('mas_fadate asc')->select(); //重新排序
		//var_dump($datalist);var_dump($yyyymm);exit;
		$this->assign("datalist",$datalist);
		
		}

		//C('SHOW_PAGE_TRACE',true);
		$this->display();
	}
	//供应商对账单（应付）
	public function ap_statement()
	{		
		$yyyy = (int)$_REQUEST['f_year'];
		$mm = (int)$_REQUEST['f_period'];
		$acc_id = $_REQUEST['acc_id'];
		$acc_title = $_REQUEST['acc_title'];
		if(!$yyyy) $yyyy=date('Y');
		if(!$mm) $mm=date('m');
		$yyyymm = (int)$yyyy * 100 + (int)$mm;
		
		$this->assign("f_year",$yyyy);
		$this->assign("f_period",$mm);
		$this->assign("acc_id",$acc_id);
		$this->assign("acc_title",$acc_title);
		
		if($yyyymm > 200001 && $acc_id)
		{
		
		$model_mas = M('Voumas');
		$model_item = D('VouitemView');
		
		$model_sp_mas = M('Spmas');
		$model_sp_dteail = D('SpdetailView');
		
		$model_check = D('FacheckitemView');
		
		$model_faccdefault = D('Faccdefault');
		
		$faccdefault = $model_faccdefault->relation(true)->where('status_flg=\'Y\' and code in (\'SINV-AP\',\'PREPAID\')')->select();
		foreach($faccdefault as $row)
		{
			$faccdef[$row['acc_code']]=$row['acc_code'];
		}
		
		//期初
		$subQuery10 = $model_mas->field('id')->where("status_flg='P' and PERIOD_DIFF(FROM_UNIXTIME(fadate, '%Y%m'), ".$yyyymm.") < 0")->select(false);
		$datalist_opening = $model_item->field('acc_code,acc_title,sum(cr-dr) as opening')
							->where("acc_code in (".implode(',',$faccdef).") and supplier_id=$acc_id  and masid in ".$subQuery10)
							->group('acc_code,acc_title')->select();
		$this->assign("datalist_opening",$datalist_opening);
		
		//本期采购、退货明细
		$subQuery21 = $model_sp_dteail->field("mas_fadate,mas_code,curr_rate,stk_code,stk_title,spec,stk_uom,qty,price,tax_rate,disc_rate,case when mas_code='RNS' then amount1*-1*curr_rate else amount1*curr_rate end as amount1,case when mas_code='RNS' then amount2*-1*curr_rate else amount2*curr_rate end as amount2,0 as amount3")
							->where("Spmas.acc_id=$acc_id and Spmas.mas_code in('PO','RNS') and PERIOD_DIFF(FROM_UNIXTIME(Spmas.fadate, '%Y%m'), ".$yyyymm.") = 0")
							->select(false);
		//付款明细（开单时直付款、退款）
		$subQuery22 = $model_sp_mas->field("fadate as mas_fadate,concat(mas_code,'-','CHECK') as mas_code,curr_rate,'' as stk_code,case when mas_code='RNS' then '在退货单上退款' else '在采购单上付款' end as stk_title,'' as spec,'' as stk_uom,0 as qty,0 as price,0 as tax_rate,0 as disc_rate,0 as amount1,0 as amount2,case when mas_code='RNS' then check_amount*-1*curr_rate else check_amount*curr_rate end as amount3")
							->where("acc_id=$acc_id and mas_code in('PO','RNS') and PERIOD_DIFF(FROM_UNIXTIME(fadate, '%Y%m'), ".$yyyymm.") = 0 and status_flg='P' and check_amount>0")
							->select(false);
		//付款明细（单独的付款）
		$subQuery23 = $model_check->field("mas_fadate,'APCHKOUT' as mas_code,curr_rate,'' as stk_code,'付款' as stk_title,'' as spec,'' as stk_uom,0 as qty,0 as price,0 as tax_rate,0 as disc_rate,0 as amount1,0 as amount2,cr as amount3")
							->where("Facheckmas.acc_id=$acc_id and Facheckmas.mas_code in('APCHKOUT') and PERIOD_DIFF(FROM_UNIXTIME(Facheckmas.fadate, '%Y%m'), ".$yyyymm.") = 0 and Facheckmas.status_flg='P' and Facheckitem.refid=0")
							->select(false);
		//调账付、退款
		$subQuery24 = $model_item->field("mas_fadate,'VOUMAS' as mas_code,curr_rate,'' as stk_code,'调整' as stk_title,'' as spec,'' as stk_uom,0 as qty,0 as price,0 as tax_rate,0 as disc_rate,0 as amount1,0 as amount2,case when cr>0 then cr else dr*-1 end as amount3")
							->where("Vouitem.acc_code in (".implode(',',$faccdef).") and Vouitem.supplier_id=$acc_id and Voumas.refcode in('VOUMAS','') and PERIOD_DIFF(FROM_UNIXTIME(Voumas.fadate, '%Y%m'), ".$yyyymm.") = 0 and Voumas.status_flg='P' and Vouitem.refid=0")
							->select(false);
		//汇兑损益
		$subQuery25 = $model_item->field("mas_fadate,'VOUMAS' as mas_code,curr_rate,'' as stk_code,'汇兑损益' as stk_title,'' as spec,'' as stk_uom,0 as qty,0 as price,0 as tax_rate,0 as disc_rate,0 as amount1,0 as amount2,case when cr>0 then cr else dr*-1 end as amount3")
							->where("curr_dr=0 and curr_cr=0 and dr-cr!=0 and Vouitem.supplier_id=$acc_id and PERIOD_DIFF(FROM_UNIXTIME(Voumas.fadate, '%Y%m'), ".$yyyymm.") = 0 and Voumas.status_flg='P' and Vouitem.refid=0")
							->select(false);
							
		//FULL
		$subQuery3 = M()->table($subQuery21.' as a1')
					->field('mas_fadate,mas_code,curr_rate,stk_code,stk_title,spec,stk_uom,qty,price,tax_rate,disc_rate,amount1,amount2,amount3')
					->union('SELECT mas_fadate,mas_code,curr_rate,stk_code,stk_title,spec,stk_uom,qty,price,tax_rate,disc_rate,amount1,amount2,amount3 FROM '.$subQuery22.' as a2',true)
					->union('SELECT mas_fadate,mas_code,curr_rate,stk_code,stk_title,spec,stk_uom,qty,price,tax_rate,disc_rate,amount1,amount2,amount3 FROM '.$subQuery23.' as a3',true)
					->union('SELECT mas_fadate,mas_code,curr_rate,stk_code,stk_title,spec,stk_uom,qty,price,tax_rate,disc_rate,amount1,amount2,amount3 FROM '.$subQuery24.' as a4',true)
					->union('SELECT mas_fadate,mas_code,curr_rate,stk_code,stk_title,spec,stk_uom,qty,price,tax_rate,disc_rate,amount1,amount2,amount3 FROM '.$subQuery25.' as a5',true)
					->select(false);

		$datalist = M()->table($subQuery3.' as a')->order('mas_fadate asc')->select(); //重新排序
		//var_dump($datalist);var_dump($yyyymm);exit;
		$this->assign("datalist",$datalist);
		
		}

		//C('SHOW_PAGE_TRACE',true);
		$this->display();
	}





}
?>